Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting a trait to objects?

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
like image 602
jokade Avatar asked Aug 20 '14 13:08

jokade


People also ask

What is a trait object?

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.

Can objects have traits?

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.

What is object safety?

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.


1 Answers

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.

like image 128
Travis Brown Avatar answered Sep 28 '22 10:09

Travis Brown