限制对象的特征?

时间:2014-08-20 13:59:37

标签: scala

有没有办法限制特征,使它只能混合到对象中? E.g。

trait OnlyForObjects {
  this: ... =>
}

object Foo extends OnlyForObjects  // --> OK

class Bar extends OnlyForObjects   // --> compile error

1 个答案:

答案 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文档中甚至没有出现。