Why is executed in this order

Hello, scala users, I’m new and I’m trying to learn Scala by doing algorithms problems, but from what I see in one example, is that one method implementation is behaving a little bit weird:

Blockquote
class A {
def doSomething() = println(“A”)
}
class B extends A {
override def doSomething() = println(“B”)
}
class C extends B {
override def doSomething() = super.doSomething(); println(“C”); println(“First??”)
}
val a: A = new C
a.doSomething()

And it prints:

Blockquote
C
First
B

Why is this happening? Thanks!

Your code is equivalent to

class C extends B:
  override def doSomething() = super.doSomething()
  println("C")
  println("First")

i.e. the doSomething() body only extends to the super invocation, and then there’s two top level println() expressions that will be evaluated right upon initialization of a C instance.

In order to extend the body of C#doSomething() as intended, delimit it with braces or, preferably, use multiple lines and indentation:

override def doSomething() =
  super.doSomething()
  println("C")
  println("First")
5 Likes

Oh, it makes sense. Thanks!!