有没有办法限制特征,使它只能混合到对象中? E.g。
trait OnlyForObjects {
this: ... =>
}
object Foo extends OnlyForObjects // --> OK
class Bar extends OnlyForObjects // --> compile error
答案 0 :(得分:20)
是的!有晦涩难懂且大多没有记载的scala.Singleton
:
scala> trait OnlyForObjects { this: Singleton => }
defined trait OnlyForObjects
scala> object Foo extends OnlyForObjects
defined module Foo
scala> class Bar extends OnlyForObjects
<console>:15: error: illegal inheritance;
self-type Bar does not conform to OnlyForObjects's selftype OnlyForObjects
with Singleton
class Bar extends OnlyForObjects
^
在language specification中有几次提及,但在API文档中甚至没有出现。