creating a new instance of a scala trait

青春壹個敷衍的年華 提交于 2019-12-11 16:58:03

问题


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.



来源:https://stackoverflow.com/questions/45241863/creating-a-new-instance-of-a-scala-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!