2017-01-20 24 views
2

這個函數看作爲一個例子:部分函數匹配的對象的引用是什麼?

def receive = { 
    case "test" => log.info("received test") 
    case _  => log.info("received unknown message") 
} 

什麼對象被匹配嗎?在箭頭的右側,我怎樣才能引用匹配的對象?

回答

4

可以與如果後衛做到這一點:

def receive: String => Unit = { 
    case str if str == "test" => println(str) 
    case _ => println("other") 
} 

Option("test").map(receive) // prints "test" 
Option("foo").map(receive) // prints "other" 

需要注意的是,如果你有,你要引用,然後像例如東西的對象foo: Foo(s)將不起作用(foo: Foo會,但是然後你失去了參考Foo的值s)。在這種情況下,你需要使用@操作:

case class Foo(s: String) 

def receive: Foo => Unit = { 
    case [email protected](s) => println(foo.s) // could've referred to just "s" too 
    case _ => println("other") 
} 

Option(Foo("test")).map(receive) // prints "test" 
0

如果你想的情況下,以匹配任何東西,都對它的引用,用一個變量名稱,而不是下劃線

def receive = { 
    case "test" => log.info("received test") 
    case other => log.info("received unknown message: " + other) 
}