I was working through the code examples from the chapter on Traits in Programming in Scala Edition1 https://www.artima.com/pins1ed/traits.html
and came across a weird behavior because of my typo. While overriding method of a trait below code snippet doesn't give any compile error although the return types of the overridden method is different Unit
vs String
. But upon calling the method on an object it returns Unit but doesn't print anything.
trait Philosophical {
def philosophize = println("I consume memory, therefore I am!")
}
class Frog extends Philosophical {
override def toString = "green"
override def philosophize = "It aint easy to be " + toString + "!"
}
val frog = new Frog
//frog: Frog = green
frog.philosophize
// no message printed on console
val f = frog.philosophize
//f: Unit = ()
But when I give the explicit return type in the overridden method , it gives a compile error:
class Frog extends Philosophical {
override def toString = "green"
override def philosophize: String = "It aint easy to be " + toString + "!"
}
override def philosophize: String = "It aint easy to be " + toString +
^
On line 3: error: incompatible type in overriding
def philosophize: Unit (defined in trait Philosophical);
found : => String
required: => Unit
Can anyone help explain why no compile error in the first case.