相关疑难解决方法(0)

如何定义"类型析取"(联合类型)?

已经一个方法被提出来处理的重载方法双定义是,以取代与模式匹配超载:

object Bar {
   def foo(xs: Any*) = xs foreach { 
      case _:String => println("str")
      case _:Int => println("int")
      case _ => throw new UglyRuntimeException()
   }
}
Run Code Online (Sandbox Code Playgroud)

这种方法要求我们放弃对参数的静态类型检查foo.能够写作会好得多

object Bar {
   def foo(xs: (String or Int)*) = xs foreach {
      case _: String => println("str")
      case _: Int => println("int")
   }
}
Run Code Online (Sandbox Code Playgroud)

我可以接近Either,但它有两种以上的快速变得难看:

type or[L,R] = Either[L,R]

implicit def l2Or[L,R](l: L): L or R = Left(l)
implicit def r2Or[L,R](r: R): L or R = …
Run Code Online (Sandbox Code Playgroud)

scala

175
推荐指数
12
解决办法
4万
查看次数

标签 统计

scala ×1