我无法用最新的dotty (0.9.0-RC1)编译以下代码,乍一看,它看起来应该.
object UnionMapping {
private def parse(string: String): Int | Double = {
if(string.contains("."))
string.toDouble
else
string.toInt
}
def test_number = {
val strings: Seq[String] = Seq("123", "2.0", "42")
// Works
val asdf: Seq[AnyVal] = strings.map(parse(_))
// Fails to compile
val union: Seq[Int | Double] = strings.map(parse(_))
}
}有谁能洞察其失败的原因,以及它的预期能否奏效?
发布于 2018-07-30 11:41:35
目前,类型推理几乎从不推断合并类型,因为它通常不是最佳选择。在您的特定示例中,我同意这样做更有意义,所以我打开了https://github.com/lampepfl/dotty/issues/4867来跟踪它。同时,通过手动指定类型参数,可以让它编译:
val union = strings.map[Int | Double, Seq[Int | Double]](parse(_))或者将联合隐藏在类型别名后面:
object UnionMapping {
type Or[A, B] = A | B
private def parse(string: String): Or[Int, Double] = {
if(string.contains("."))
string.toDouble
else
string.toInt
}
def test_number = {
val strings: Seq[String] = Seq("123", "2.0", "42")
val union = strings.map(parse(_))
// infered type for union is Seq[Or[Int, Double]]
}
}https://stackoverflow.com/questions/51575183
复制相似问题