-
1 # 使用者1285949842971
-
2 # 我是阿嘛
(1 to 10) map { case x => 2*x }
中的{ case x => 2*x } 得到的是一個PartialFunction 。然而,事實並非如此。
簡單說,凡是Scala中出現如下表達式時:
{ case p1 => e1; case p2 => e2; ...; case pn => en }
其結果為Scala中的匿名函式(Anonymous Function) ,但是其具體型別是根據其所處位置而定,可能是一個FunctionN,也可能是一個PartialFunction (這裡的FunctionN指的是非PartialFunction的Function)。
下面用一段小程式碼證明之:
scala> def needfunc[F](f: F) = fneedfunc: [F](f: F)Fscala> needfunc[PartialFunction[Int, Int]]({ case x => 2*x }).getClass.getSuperclasswarning: there was one feature warning; re-run with -feature for detailsres0: Class[?0] forSome { type ?0 >: ?0; type ?0
上面的結果表明,當我需要一個Function(非PartialFunction)時,我得到的就是一個非PartialFunction的Function;當我需要一個PartialFunction時,得到就是PartialFunction。
當然,我不是僅有上面的例子就下結論。實際上,《Scala語言規範》(Scala Language Specification)對此有具體規定,引用如下:Pattern Matching
Pattern Matching Anonymous Functions
BlockExpr ::= `{" CaseClauses `}"
An anonymous function can be defined by a sequence of cases
{ case p1 => b1; …… case pn => bn }
which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionkk[S1,…,Sk, R] for some k>0, or scala.PartialFunction[S1, R], where the argument type(s) S1,…,Sk must be fully determined, but the result type R may be undetermined.
為啥需要搞清什麼時候是PartialFunction而什麼時候是FunctionN呢,這裡涉及另一個問題:PartialFunction在某些時候相對FunctionN會存在效能問題!
這是另一個有趣的問題了。
回覆列表
看了一下幾位的回答,包括 @hongjiang@Jaco@白喬@Geek.cs 都認為如下程式碼中的
中的{ case x => 2*x } 得到的是一個PartialFunction 。然而,事實並非如此。簡單說,凡是Scala中出現如下表達式時:其結果為Scala中的匿名函式(Anonymous Function) ,但是其具體型別是根據其所處位置而定,可能是一個FunctionN,也可能是一個PartialFunction (這裡的FunctionN指的是非PartialFunction的Function)。下面用一段小程式碼證明之:上面的結果表明,當我需要一個Function(非PartialFunction)時,我得到的就是一個非PartialFunction的Function;當我需要一個PartialFunction時,得到就是PartialFunction。當然,我不是僅有上面的例子就下結論。實際上,《Scala語言規範》(Scala Language Specification)對此有具體規定,引用如下:Pattern MatchingPattern Matching Anonymous FunctionsAn anonymous function can be defined by a sequence of cases
which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionkk[S1,…,Sk, R] for some k>0, or scala.PartialFunction[S1, R], where the argument type(s) S1,…,Sk must be fully determined, but the result type R may be undetermined.
為啥需要搞清什麼時候是PartialFunction而什麼時候是FunctionN呢,這裡涉及另一個問題:PartialFunction在某些時候相對FunctionN會存在效能問題!這是另一個有趣的問題了。