type "exists" without specifying exactly what it is.
The type parameters of generics are erased in JVM byte code. For example, when a
List[Int] is created, the Int type is not available in the byte code, so at runtime it's not
possible to distinguish between List[Int] and a List[String], based on the known type
information.
object Doubler{
def double(seq: Seq[_]): Seq[Int] =
seq match{ case Nil = Nil case head +: tail = (toInt(head)*2)+:double(tail) } private def toInt(x:Any):Int =
x match{ case i:Int = i case s:String = s.toInt case x = throw new RuntimeException(s"Unexpected list element $x") } }
The expression Seq[_] is actually shorthand for the existential type, Seq[T] forSome {type T}.
T can be any subtype of Any. Existential types exist primarily to support Java generics while preserving correctness in Scala's type system.
No comments:
Post a Comment