首页 > 解决方案 > 匿名模式匹配函数的转换

问题描述

我观察到 Scala 匿名模式匹配函数的行为很神奇,如以下代码所示:

trait MyFunction {
  def map(value: String): String
}
val f1: MyFunction = { case e: String => e.toLowerCase() }
val f: Function[String, String] = { case e: String => e.toLowerCase() }
val f2: MyFunction = f
val pf: PartialFunction[String, String] = { case e: String => e.toLowerCase() }
val f3: MyFunction = pf

第一个赋值,从函数到MyFunction,确实编译。根据https://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-matching-anonymous-functions,匿名模式匹配函数的类型是Functionor PartialFunction。但是,当我首先将表达式分配给Functionor的实例PartialFunction,然后分配给MyFunction时,它不会编译,使用

Expression of type Function[String, String] doesn't conform to expected type MyFunction

所以我的问题是 -f1编译赋值的魔力是什么?2.11、2.12 和 2.13 中的行为似乎相同。

标签: scala

解决方案


推荐阅读