2010-03-09 15 views
13

基本上,我希望能夠建立一個自定義提取器,而不必在使用它之前將它存儲在變量中。可以使用case語句(或使用提取器的任何其他地方)中的參數來定製提取器嗎?

這不是我如何使用它的真實例子,它更可能用於正則表達式或其他字符串模式(如構造)的情況,但希望它解釋我在尋找什麼:

def someExtractorBuilder(arg:Boolean) = new { 
    def unapply(s:String):Option[String] = if(arg) Some(s) else None 
} 

//I would like to be able to use something like this 
val {someExtractorBuilder(true)}(result) = "test" 
"test" match {case {someExtractorBuilder(true)}(result) => result } 

//instead I would have to do this: 
val customExtractor = someExtractorBuilder(true) 
val customExtractor(result) = "test" 
"test" match {case customExtractor(result) => result} 

如果只是做一個單獨的定製提取它並沒有太大的差別,但如果你正在構建提取的大名單的case語句,它可以使事情變得更加困難讀通過分離所有的從他們的使用提取器。

我想到的是,答案是否定的,你不能這樣做,但我想我會四處打聽第一:d

+0

你呢,呃,*試試*它? – 2010-03-09 19:04:24

+0

我曾嘗試它,我收到一個語法錯誤: 階> VAL {someExtractorBuilder(真)}(結果)= 「測試」 :1:錯誤:簡單圖案 val的非法啓動{someExtractorBuilder(真)} (result)=「test」 ^ – 2010-03-09 19:43:53

+0

你最終想做什麼?可能有更好的方法來做它比製造大量的提取器。 – 2010-03-10 05:24:50

回答

2

都能跟得上。

8.1.7提取模式

An extractor pattern x (p 1 , . . . , p n) where n ≥ 0 is of the same syntactic form as a constructor pattern. However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matches the pattern.

7

參數化的提取會很酷,但我們沒有足夠的資源,現在要實現它們。

+1

感謝您關注這些問題:-) – Lutz 2011-07-08 09:34:41

1

人們可以自主使用隱式參數提取器在一定程度上,這樣的:

object SomeExtractorBuilder { 
    def unapply(s: String)(implicit arg: Boolean): Option[String] = if (arg) Some(s) else None 
} 

implicit val arg: Boolean = true 
"x" match { 
    case SomeExtractorBuilder(result) => 
    result 
} 

不幸的是,當你想在一個match使用不同的變種這個不能用,因爲所有case語句在相同的範圍內。儘管如此,它有時也很有用。

相關問題