模式匹配/检查Function1的Arity

时间:2015-04-02 14:28:30

标签: scala

考虑以下方法:

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

是否可以在List[Any] => Any上进行模式匹配?我在Function1上看不到unapply方法,所以我认为答案是否定的。

这是我想要做的事情:

示例:

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

也许我可以找出arity的{​​{1}}来区分x: Any与其他所有内容(List[Any] => Any)?

编辑

我希望我不必依赖_ == f.toString

2 个答案:

答案 0 :(得分:5)

不,由于类型删除,您无法在List[Any] => Any上完全匹配,但您可以在Function1本身匹配:

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

任何其他匹配,例如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

答案 1 :(得分:3)

即使没有unapply方法,您也可以完全匹配类型:

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

然后你可以检查:

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