2013-05-30 57 views
1

相同的變量說我有以下Scala的匹配,解決來自兩個不同的圖案

case class IntWrap(value:Int) 

我想從2案件提取相同的變量,如下所示:

x match { 
    case value:Int | IntWrap(value) => dosomethingwith(x) 
    case _ => ??? 
} 

但只這樣,我已經能夠做到這一點是:

x match { 
    case value:Int => dosomethingwith(x) 
    case IntWrap(value) => dosomethingwith(x) 
    case _ => ??? 
} 

有沒有更好的辦法,因爲在我的現實生活中的情況下dosomethi ng實際上是一個很大的代碼塊,不容易封裝。

+0

請記住,函數可以嵌套,所以如果dosomething「不容易封裝」,因爲它使用方法的局部變量或參數,您可以在匹配之前定義它並訪問相同的變量。 –

回答

2

如果真的是你想要做的事與x,不與提取value的話,那麼下面將工作:

case class IntWrap(value:Int) // extends T 

def dosomethingwith(x: Any) = x 

val x: Any = IntWrap(101) 

x match { 
    case _: Int | _: IntWrap => dosomethingwith(x) 
    case _ => ??? 
} 


如果你真的想與提取價值的工作,你可以分析出相應的匹配塊到自己的提取和重用任何必要:

x match { 
    case Unwrap(value) => dosomethingwith(value) 
    case _ => ??? 
} 

object Unwrap { 
    def unapply(x: Any) = x match { 
    case x: Int => Some((x)) 
    case IntWrap(value) => Some((value)) 
    case _ => None 
    } 
} 
0

老實說,我看不出與方式的問題你重新做事。只要dosomethingwith是一個單獨的功能,那麼我沒有看到任何重複代碼的問題。如果你的代碼看起來像這樣,然後我看不出有任何需要拿出與其他解決方案:

def foo(x:Any){ 
    x match { 
    case value:Int => dosomethingwith(value) 
    case IntWrap(value) => dosomethingwith(value) 
    case _ => ??? 
    } 
} 

def dosomethingwith(x:Int){ 
    //do something complicated here... 
} 
0

我想出了某事有點不同,但它可以幫助你避免重複:

case class IntWrap(value: Int) 
    implicit def intWrapToInt(intWrap: IntWrap) = intWrap.value 

    def matchInt(x: AnyVal) = x match { 
    case i: Int => println("int or intWrap") 
    case _ => println("other") 
    } 

    //test 
    matchInt(IntWrap(12))   //prints int or intWrap 
    matchInt(12)     //prints int or intWrap 
    matchInt("abc")    //prints other 

雖然它不適用於每個參考。所以,小心點。

相關問題