Scala 模式匹配函数 - 如何绕过类型擦除

scala pattern match a function - how to get around type erasure

我想模式匹配一​​个函数,问题是类型擦除。请注意在下面的代码片段中,尽管 warning 发出了匹配项,但匹配项仍然是 "wrong"。

scala> def f1 = ()=>true
f1: () => Boolean

scala> val fl = f1
fl: () => Boolean = <function0>

scala>

scala> fl match {
     | case fp :Function0[Boolean] => 1
     | case _ => 2
     | }
res8: Int = 1

scala>

scala> fl match {
     | case fp :Function0[String] => 1
     | case _ => 2
     | }
<console>:11: warning: fruitless type test: a value of type () => Boolean cannot also be a () => String (but still might match its erasure)
              case fp :Function0[String] => 1
                       ^
res9: Int = 1

scala>

我能想出的是 class 包装函数的案例。我得到类型安全,注意下面的错误。 但是,首先,这是不雅的,其次,我不明白案例 class 如何强制类型,而模式比赛不能。我唯一的猜测是案例 class 受编译器保护并且匹配仅在运行时解决

scala> case class FunctionWrapper(fn: ()=>Boolean)
defined class FunctionWrapper

scala> val fw = FunctionWrapper(fl)
fw: FunctionWrapper = FunctionWrapper(<function0>)

scala> def fs = ()=>"whatever"
fs: () => String

scala> val fws = FunctionWrapper(fs)
<console>:10: error: type mismatch;
 found   : () => String
 required: () => Boolean
       val fws = FunctionWrapper(fs)
                                 ^

scala> fw match {
     | case FunctionWrapper(f) => f()
     | case _ => false
     | }
res10: Boolean = true

综上所述,我想知道是否有一种优雅的方式来对函数进行模式匹配,也许可以理解为什么上面的例子会这样

这里的警告实际上有两个方面:

1) 首先,"a value of type () => Boolean cannot also be a () => String":确实你在匹配一个 () => Boolean 并且它永远不可能同时是一个 () => String 所以这种情况没有意义,并且在一个理想的世界中永远不应该匹配。然而,擦除开始发挥作用,因为第二部分暗示

2) “(但仍然可能匹配它的擦除)”:这里的擦除意味着 () => Boolean 的实例(又名 Function0[Boolean])和 () => String 的实例(又名 Function0[String]) 在运行时表示完全相同。因此没有办法区分它们,当你在现实中对 Function0[String] 进行模式匹配时,编译器只能告诉它它是 some Function0 但不知道它是否是 Function0[Boolean]Function0[String].

诚然,警告的第二部分在这里很容易被忽略。 如果输入 fl Any,警告的第一部分将不适用,您会收到更有用的消息:

scala> (fl:Any) match {
     |   case fp :Function0[Boolean] => 1
     |   case _ => 2
     | }
<console>:11: warning: non-variable type argument Boolean in type pattern () => Boolean is unchecked since it is eliminated by erasure
            case fp :Function0[Boolean] => 1

至于解决方案,除了确实包装函数实例外,您无能为力。幸运的是,您不需要为每种可能的 return 类型编写一个特定的包装器。 Scala 提供 ClassTagTypeTag 来绕过擦除,我们可以通过将其存储在(通用)函数包装器中来利用它。然而,它仍然使用起来相当麻烦,并且在不安全方面会犯错误,因为你必须匹配存储在包装器中的 ClassTag/TypeTag,并强制转换(直接通过 asInstanceOf 或间接通过相同的模式匹配)函数到相应的函数类型。

简短的回答:您必须撤消擦除以使用 TypeTag 来具体化类型。

I don't understand how the case class can enforce types whereas the pattern match can't.

因为你的案例class没有类型参数。只有通用类型被擦除,这就是为什么它被称为“部分擦除”。

相关问题:Generic unapply method for different types of List。以下代码与那里的答案之一基本相同,但使用函数而不是列表:

import scala.reflect.runtime.universe._

def foo[A : TypeTag](a: A): Int = typeOf[A] match {
  case t if t =:= typeOf[Int => Int] => a.asInstanceOf[Int => Int](0)
  case t if t =:= typeOf[Boolean => Int] => a.asInstanceOf[Boolean => Int](true)
  case _ => 3
}

foo((i: Int) => i + 1)
// res0: Int = 1

foo((b: Boolean) => if (b) 2 else 0)
// res1: Int = 2

foo((b: Boolean) => !b)
// res2: Int = 3

我不确定是否有办法编写一个提取器来使匹配块更好。

如果您需要以丢失静态类型信息的方式传递这些函数(将它们推入 Function[_, _] 的集合中,使用 then 作为 Akka 消息等),那么您需要传递标签周围太:

import scala.reflect.runtime.universe._

case class Tagged[A](a: A)(implicit val tag: TypeTag[A])

def foo[A, B](tagged: Tagged[A => B]): Int = tagged.tag.tpe match {
  case t if t =:= typeOf[Int => Int] => tagged.a.asInstanceOf[Int => Int](0)
  case t if t =:= typeOf[Boolean => Int] => tagged.a.asInstanceOf[Boolean => Int](true)
  case _ => 3
}
foo(Tagged((i: Int) => i + 1))
// res0: Int = 1

foo(Tagged((b: Boolean) => if (b) 2 else 0))
// res1: Int = 2

foo(Tagged((b: Boolean) => !b))
// res2: Int = 3