我无法获得以下代码来编译最新的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(_))
}
}
有人对它为什么会失败以及它是否预期工作有任何见识吗?
答案 0 :(得分:1)
当前,类型推断几乎永远不会推断联合类型,因为它通常不是最佳选择。在您的特定示例中,我同意这样做会更有意义,因此我打开了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]]
}
}