【发布时间】:2013-12-18 03:06:32
【问题描述】:
我正在查看Scala in Depth 中的这个Named Arguments 示例:
scala> class Parent {
| def foo(bar: Int = 1, baz: Int = 2): Int = bar + baz
| }
defined class Parent
scala> class Child extends Parent {
| override def foo(baz: Int = 3, bar: Int = 4): Int = super.foo(baz, bar)
| }
defined class Child
scala> val p = new Parent
p: Parent = Parent@6100756c
scala> p.foo()
res1: Int = 3
scala> val x = new Child
x: Child = Child@70605759
调用 x.foo() 的结果为 7,因为 Child#foo 的默认参数为 3 和 4。
scala> x.foo()
res3: Int = 7
在运行时实例化一个新的Child,但在编译时实例化Parent。 这可能正确也可能不正确
scala> val y: Parent = new Child
y: Parent = Child@540b6fd1
调用 x.foo() 计算结果为 7,因为 Child#foo 的默认参数为 3 和 4。
scala> y.foo()
res5: Int = 7
调用 x.foo() 的结果为 4,因为 Child#foo 的默认 baz 参数为 3。
scala> x.foo(bar = 1)
res6: Int = 4
但是,我不明白为什么 y.foo(bar = 1) 返回 5。我希望 Child#foo 会被评估,因为 y 是 Child 类型。将1的bar传入foo意味着baz的默认值为3。所以它应该产生4。但我的理解当然是不正确的。
scala> y.foo(bar = 1)
res7: Int = 5
【问题讨论】:
标签: scala