# Scala的存在类型

04/11 20:54

Scala的存在类型

Seq[_] Seq[T] forSome {type T} T 可以是Any 的任意子类
Seq[_ <: A] Seq[T] forSome {type T <: A} T 可以是A（在某处已经定义了）的任意子类
Seq[_ >: Z <: A] Seq[T] forSome {type T >: Z <: A} T 可以是A 的子类且是Z 的超类

``````object Doubler {
def double(seq: Seq[String]): Seq[Int] = double(seq map (_.toInt))
def double(seq: Seq[Int]): Seq[Int] = seq map (_*2)
}``````

``````Error:(3, 7) double definition:
def double(seq: Seq[String]): Seq[Int] at line 12 and
def double(seq: Seq[Int]): Seq[Int] at line 13
have same type after erasure: (seq: Seq)Seq
def double(seq: Seq[Int]): Seq[Int] = seq map (_*2)``````

``````object Doubler {
def double(seq: Seq[_]): Seq[Int] = seq match {
case Nil => Nil
}

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")
}
}``````

``type Seq[+A] = scala.collection.Seq[A]``

``````def double(seq: Seq): Seq[Int] = seq match {
case Nil => Nil
}``````

util.List[_ <: A] 的表达式在结构上与Java 的表达式java.util.List<? extends A>的类似之处。

1
0 收藏

0 评论
0 收藏
1