Scala Named Arguments

Viewed 736

I'm looking at this Named Arguments example in Scala in Depth:

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

Calling x.foo() evaluates to 7 since Child#foo has default arguments of 3 and 4.

scala> x.foo()
res3: Int = 7

Instantiate a new Child at run-time, but Parent at compile-time. This may or may not be correct

scala> val y: Parent = new Child
y: Parent = Child@540b6fd1

Calling x.foo() evaluates to 7 since Child#foo has default arguments of 3 and 4.

scala> y.foo()
res5: Int = 7

Calling x.foo() evaluates to 4 since Child#foo has a default baz argument of 3.

scala> x.foo(bar = 1)
res6: Int = 4

However, I don't understand why y.foo(bar = 1) returns 5. I would've expected Child#foo to be evaluated since y is a Child type. Passing in a bar of 1 to foo means that baz's default is 3. And so it should produce 4. But my understanding is of course incorrect.

scala> y.foo(bar = 1)
res7: Int = 5
1 Answers
Related