有没有办法限制特征,使其只能混合到对象中?例如
trait OnlyForObjects {
this: ... =>
}
object Foo extends OnlyForObjects // --> OK
class Bar extends OnlyForObjects // --> compile error
最佳答案
是的!有一个晦涩难懂且几乎没有记录的 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 文档中。
关于scala - 将特征限制为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25406698/