1
votes

I am trying to understand when I create Class that extends a Trait which I believe extends Function0 [() => Unit] why does an instantiation of an object for that class is of type Function0? Is the apply method invoked as a constructor during object instantiation? I am not able to fully comprehend the mechanics of the below code.

scala> trait Base extends (() => Unit) {
 |
 |    def label: String
 | }
defined trait Base

scala> class Extend extends Base{
 | override def label = "Hello label"
 | override def apply()= println ("This is apply")
 |
 | }
defined class Extend

scala> val m = new Extend
m: Extend = <function0>

scala> m()
This is apply
1

1 Answers

2
votes

The <function0>-thing is not the type. That's just the output of the default toString method defined on Function0. You don't override the toString anywhere, so it uses the implementation from the superclass. Adding methods like label doesn't change anything, the compiler cannot read (your thoughts).

Little demo:

scala> val f = new Function0[Int]{ def apply(): Int = 42 }
f: () => Int = <function0>

scala> f.toString
res0: String = <function0>

On the other hand, the type in your example is correctly shown as Extend.