限制对象的特征?

jok*_*ade 10 scala

有没有办法限制特征,使其只能混合到对象中?例如

trait OnlyForObjects {
  this: ... =>
}

object Foo extends OnlyForObjects  // --> OK

class Bar extends OnlyForObjects   // --> compile error
Run Code Online (Sandbox Code Playgroud)

Tra*_*own 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
                         ^
Run Code Online (Sandbox Code Playgroud)

它在语言规范中提到了几次,但是甚至没有出现在API文档中.

  • 哈!我已经开始期待使用疯狂语言功能的完全疯狂和惊人的答案,但我现在看到我们已经转向*secret*功能. (3认同)
  • 那是_Yes!_ eta-扩展到_finally有人问过这个!_. (3认同)