如何定義“類型分離”(聯合類型)?有一種方法建議處理重載方法的雙重定義是將重載替換為模式匹配:object Bar {
def foo(xs: Any*) = xs foreach {
case _:String => println("str")
case _:Int => println("int")
case _ => throw new UglyRuntimeException()
}}這種方法要求我們提交對參數的靜態類型檢查。foo..如果能寫的話會好得多object Bar {
def foo(xs: (String or Int)*) = xs foreach {
case _: String => println("str")
case _: Int => println("int")
}}我可以接近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 = Right(r)object Bar {
def foo(xs: (String or Int)*) = xs foreach {
case Left(l) => println("str")
case Right(r) => println("int")
}}它看起來像是一個通用的(優雅的,高效的)解決方案需要定義Either3, Either4..有誰知道實現同樣目的替代解決方案嗎?據我所知,Scala沒有內置的“類型分離”。另外,上面定義的隱式轉換是否潛伏在某個標準庫中,以便我只需導入它們?
3 回答
慕容708150
TA貢獻1831條經驗 獲得超4個贊
Any*
class StringOrInt[T]object StringOrInt {
implicit object IntWitness extends StringOrInt[Int]
implicit object StringWitness extends StringOrInt[String]}foo
object Bar {
def foo[T: StringOrInt](x: T) = x match {
case _: String => println("str")
case _: Int => println("int")
}}foo(5)foo("abc")foo(true)StringOrInt[Boolean]StringOrInta sealed
T: StringOrIntStringOrInt[T]
紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
scala> def f[A](a: A)(implicit ev: (Int with String) <:< A) = a match {
| case i: Int => i + 1
| case s: String => s.length | }f: [A](a: A)(implicit ev: <:<[Int with String,A])Intscala> f(3)res0:
Int = 4scala> f("hello")res1: Int = 5scala> f(9.2)<console>:9: error: Cannot prove that Int with String <:< Double.
f(9.2)
^資料來源:
添加回答
舉報
0/150
提交
取消
