Wisely or not, I'm writing a method that I'd like to accept only Scala singletons, i.e. objects implemented via "object" rather than constructed instances of a class or trait. It should accept Scala singletons of any type, so "MySingleton.type" won't do.
I came upon the very strange construct "scala.Singleton", which is not documented in the api docs, but seems to do the trick:
scala> def check( obj : Singleton ) = obj
check: (obj: Singleton)Singleton
scala> check( Predef )
res0: Singleton = scala.Predef$@4d3e9963
scala> check ( new java.lang.Object() )
<console>:9: error: type mismatch;
found : java.lang.Object
required: Singleton
check ( new java.lang.Object() )
scala> check( Map )
res3: Singleton = scala.collection.immutable.Map$@6808aa2d
scala> check( Map.empty[Any,Any] )
<console>:9: error: type mismatch;
found : scala.collection.immutable.Map[Any,Any]
required: Singleton
check( Map.empty[Any,Any] )
However, rather inexplicably (to me), String literals are accepted as Singletons while explicitly constructed Strings are not:
scala> check( "foo" )
res7: Singleton = foo
scala> check( new String("foo") )
<console>:9: error: type mismatch;
found : java.lang.String
required: Singleton
check( new String("foo") )
Why do String literals conform to Singleton? Am I misunderstanding what the Singleton type is supposed to specify?