0
這兩個部分功能是否等同?Scala:這兩個部分功能是否相同?
val f0: PartialFunction[Int, String] = {
case 10 => "ten"
case n: Int => s"$n"
}
val f1 = new PartialFunction[Int, String] {
override def isDefinedAt(x: Int): Boolean = true
override def apply(v: Int): String = if (v == 10) "ten" else s"$v"
}
UPD
val pf = new PartialFunction[Int, String] {
def isDefinedAt(x: Int) = x == 10
def apply(v: Int) = if (isDefinedAt(v)) "ten" else "undefined"
}
def fun(n: Int)(pf: PartialFunction[Int, String]) = pf.apply(n)
println(fun(100)(pf))
這真的PF現在?
它們肯定總會有相同的行爲,但可能在字節碼中表示不同,具體取決於所使用的scala編譯器的版本。你在問什麼?這些也不是嚴格的局部函數,因爲它們總是被定義的... – jazmit
我沒有得到這個'因爲它們總是被定義的'。你什麼意思? – Finkelson
我需要添加'def fun(n:Int)(pf:PartialFunction [Int,String]):String = pf.apply(n)'來製作f0和f1 PartialFunctions? – Finkelson