开发者

Scala 2.8 - Potential problem with named arguments

Consider the following code :

// My code
class Person(var age: Int)

// Client's code
object Main {
  def main(args: Array[String]) {
    val p = new Person(age = 18)
    println(p.age)
  }
}

Now say later I need to define an accessor method for the age field.

However trying to do something like below isn't legal as field names and method names share the same namespace in Scala :

// *** DOES NOT COMPILE ***
// My code
class Person(age: Int) {
  def age = /* some code that gives integer */
}

// Client's code
object Main {
  def main(args: Array[String]) {
    val p = new Person(age = 18)
    println(p.age)
  }
}

So I need to rename either the constructor argument age or my field age. Either way I will be breaking the client code, isn't it?

Is there any possible w开发者_运维知识库ork around this? Or is this an inherent problem with named arguments?

Please shed some light on this. Any help would be greatly appreciated.

Thanks.


The second code block does compile, provided you put something in place of the /* some code that gives integer */ placeholder comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜