2015-04-02 57 views
-2

的元數考慮以下方法:模式匹配/檢查功能1

scala> def f: List[Any] => Any = xs => 1234 // this output does not matter 
f: List[Any] => Any 

是否有可能模式匹配上List[Any] => Any?我沒有看到Function1unapply方法,所以我認爲答案是否定的。

以下是我正在試圖做的:

例子:

def foo(x: Any) = x match { 
    case ... // to handle the case of List[Any] => Any]? 
    case ... 
} 

也許我可以計算出的x: AnyarityList[Any] => Any對一切(_)之間進行區分?

編輯

我希望我不必依靠f.toString == <function1>

回答

5

不,你不能完全匹配上List[Any] => Any由於類型擦除,但你可以匹配Function1本身:

def foo(x: Any): String = x match { 
    case _: Function1[_, _] => "some function1" 
    case _ => "other" 
} 

y其他匹配,如case _: (List[Any] => Any) => "function from list to any"將與case _: Function1[_, _] => "some function"相同:

scala> def foo(x: Any): String = x match { 
    |  case _: (List[Any] => Any) => "function from list to any" 
    |  case _ => "other" 
    | } 
<console>:8: warning: non-variable type argument List[Any] in type pattern List[Any] => Any is unchecked since it is eliminated by erasure 
      case _: (List[Any] => Any) => "function from list to any" 
          ^
foo: (x: Any)String 

scala> def aaa(l: Any): Any = null //it's `Any => Any` - not `List[Any] => Any`!! 
aaa: (l: Any)Any 

scala> foo(aaa _) 
res11: String = function from list to any 

scala> foo(1) 
res12: String = other 
+0

謝謝。順便說一句,我添加另一'密封trait'和2'情況class''es,其中之一有一個'功能1 [任意,不限]'參數。這阻止了我投射。 – 2015-04-03 15:47:01

3

您可以在類型純粹匹配,即使沒有unapply方法:

def foo(x: Any): String = x match { 
    case _: (Any => Any) => "some function1" 
    case _ => "other" 
} 

然後你可以檢查:

foo(f) //"some function1" 
foo(1) //"other"