creating a new instance of a scala trait

2019-08-19 03:32发布

问题:

Please explain this in Scala.

If I have a

 trait A

I cannot do a

val a = new A

But this example trait,

 trait DS[-In, +Out]{def apply(i: In): Out}

can have an instance of

val t1 = new DS[Any, Int]{def apply(i: Any) = i.toString.toInt}

How is this allowed?

回答1:

Works just fine with a class body {}.

val a = new A {}


回答2:

What is happening is that by providing a class body you are creating an anonymous class inline that extends the trait.



标签: scala traits