Is there a way to restrict a trait so that it can only be mixed into objects? E.g.
trait OnlyForObjects {
this: ... =>
}
object Foo extends OnlyForObjects // --> OK
class Bar extends OnlyForObjects // --> compile error
Yes! There's the obscure and mostly undocumented 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
^
It's mentioned a few times in the language specification, but doesn't even appear in the API documentation.