8.4. Typy singletonowe
Jeżeli x jest obiektem albo instancją jakiejś klasy dziedziczącej z AnyRef, to x.type oznacza typ singletonowy. Taki typ może przyjmować wartość x lub wartość null.
scala> object A defined object A scala> var c: A.type = null c: A.type = null scala> c = A c: A.type = A$@74f125 scala> val d = A d: A.type = A$@74f125 scala> c = d c: A.type = A$@74f125
W poniższym przykładzie nie można przypisać wartości „Peter” zmiennej b, gdyż ta ma typ singletonowy a.type.
scala> val a = "John" a: String = John scala> var b: a.type = a b: a.type = John
scala> b = null b: a.type = null scala> b = "Peter" <console>:12: error: type mismatch; found : String("Peter") required: a.type b = "Peter" ^
Typy singletonowe są zgodne z typem scala.Singleton.
scala> val e: Singleton = c e: Singleton = A$@74f125 scala> c.isInstanceOf[Singleton] res0: Boolean = true
Specyfikacja języka Scala opisuje typy singletonowe w punkcie 3.2.1. |