点序列映射到联合

dotty seq mapping to union

我无法获取以下代码以使用最新的 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(_))
  }

}

有没有人知道它失败的原因以及它是否可以正常工作?

目前,类型推断几乎从不推断联合类型,因为它通常不是最佳选择。在您的特定示例中,我同意这样做会更有意义,因此我打开了 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]]
  }

}