2015-05-29 38 views
1

鑑於以下PartialFunction ...斯卡拉:如何定義與默認值的參數在部分功能

type MyFunc = PartialFunction[(Int, Int), String] 

... 

val myFunc = MyFunc { 
    case (i, j) => (i + j).toString 
} 

... 

myFunc(3, 2) // returns "5" 

...是有辦法有第二個參數(j)的默認值?到目前爲止,我發現的唯一方法是這樣的:

type MyFunc = PartialFunction[Int, String] 

... 

def myFunc(j: Int = 10) = MyFunc { 
    case i => (i + j).toString 
} 

... 

myFunc()(5) // returns "15" 
myFunc(5)(2) // returns "7" 

上面的解決方案意味着不同的PartialFunction和方法,這需要有默認值的參數...但它不正是我要找對於。有更好的選擇嗎?

回答

1

如果我理解正確的問題,這個怎麼樣?

object WrapperFunc { 
    val f = PartialFunction[(Int, Int), String] { 
    case (i,j) => (i + j).toString 
    } 
def apply(a: Int, b: Int = 5) = f (a,b) 
} 
WrapperFunc(1) 
WrapperFunc(1,2) 
2

方法可以有默認參數,但函數不能。

你的第二個def myFunc是一個方法(因此它可以有可選的參數),但是你不能將它擴展到一個函數中。

def mymethod(j: Int = 10) = MyFunc { 
    case i => (i + j).toString 
} 

val asFunc = mymethod _ 

將失去默認參數。

如果你想有這樣的事情,你會需要這樣的東西

type MyFunc = PartialFunction[(Option[Int], Int), String] 

val myFunc = MyFunc { 
    val mydefault = 10 
    case (i, j) => (i.getOrElse(mydefault) + j).toString 
} 

,並把它作爲myfunc((Some(8), 3))myfunc((None, 3))