随着 Ceylon 1.0 的发布,一些人正在讨论联合类型的用处。我想知道您可以编写以下代码多么简洁:
String test(String | Integer x) {
  if (x is String) {
     return "found string";
  } else if (x is Integer) {
     return "found int";
  }
  return "why is this line needed?";
}
print(test("foo bar"));  // generates 'timeout'... well, whatever
...在斯卡拉?我的想法是这样的:
type | [+A, +B] = Either[A, B]
object is {
  def unapply[A](or: Or[A]): Option[A] = or.toOption
  object Or {
    implicit def left[A](either: Either[A, Any]): Or[A] = new Or[A] {
      def toOption = either.left.toOption
    }
    implicit def right[A](either: Either[Any, A]): Or[A] = new Or[A] {
      def toOption = either.right.toOption
    }
  }
  sealed trait Or[A] { def toOption: Option[A] }
}
def test(x: String | Int) = x match {
  case is[String](s) => "found string"   // doesn't compile
  case is[Int   ](i) => "found int"
}
但是模式提取器无法编译。有任何想法吗?
我知道一些工作答案存在类似的问题,但我特别想知道是否可以使用类型别名Either和提取器。即使定义了除 之外的新类型类Either,解决方案也应允许详尽的模式匹配。