【发布时间】:2013-11-14 13:05:00
【问题描述】:
随着 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
...在 Scala 中?我的想法是这样的:
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"
}
但模式提取器无法编译。有什么想法吗?
我知道that a similar question exists 有一些可行的答案,但我特别想知道是否可以为Either 和提取器使用类型别名。即使定义了Either 以外的新类型类,该解决方案也应该允许详尽 模式匹配。
【问题讨论】:
-
@AlexIv 是的,这也包含在链接的问题中。
size的最终定义的问题是模式匹配器不知道类型。例如,您可以在没有警告的情况下离开case s: String案例。您可以添加一个无用的案例,如case b: Boolean而不会出错。 -
据我了解,unapply issues.scala-lang.org/browse/SI-884 中不允许使用类型参数
-
@SergeyPassichenko 好的,谢谢!在我的第二次尝试中(下面作为“答案”),我有一个不使用类型应用程序的模式。也许这是一个更好的解决方案起点。