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
A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of an object safe base trait plus any number of auto traits. Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
Object Safety The error says that Clone is not 'object-safe'. Only traits that are object-safe can be made into trait objects. A trait is object-safe if both of these are true: the trait does not require that Self: Sized. all of its methods are object-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With