Reputation: 13352
object Initialization {
def main(args: Array[String]): Unit = {
val list = Traversable(1,2,4,5)
//list.foreach(println)
println( list.getClass.getSimpleName )
}
}
It prints $colon$colon
, but I expected something like List
. What does this obscure name mean?
Upvotes: 3
Views: 156
Reputation: 33029
That's because List
is a sealed superclass that is over case class ::
and object Nil
(see the known subclasses section under the List documentation). ::
is pronounced cons, being named after the list cons operator in most traditional functional programming languages.
Since your list head is actually an instance of the ::
case class, and Scala uses name mangling to represent non-word class names on the JVM, you end up with $colon$colon
when you use reflection to get the name.
Update: I'm not exactly sure what you're trying to use the class name for, but you might be able to use stringPrefix
instead. It's defined for anything extending GenTraversableLike
, which will be pretty much every Scala collection type.
If you're trying to do control flow with the class name, you should probably try something else. Pattern matching would work nicely, e.g.:
xs match {
list: List[_] => // do list stuff
set: Set[_] => // do set stuff
}
Upvotes: 6