scala - 匿名模式匹配函数的转换
问题描述
我观察到 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,匿名模式匹配函数的类型是Function
or PartialFunction
。但是,当我首先将表达式分配给Function
or的实例PartialFunction
,然后分配给MyFunction
时,它不会编译,使用
Expression of type Function[String, String] doesn't conform to expected type MyFunction
所以我的问题是 -f1
编译赋值的魔力是什么?2.11、2.12 和 2.13 中的行为似乎相同。
解决方案
推荐阅读
- java - Spring通过注释为当前用户传递参数值
- javascript - 如何在传单中启用/禁用位置监视?
- angular - GET http://localhost:4200/undefined 同时显示来自 firebase 的图像
- python - 在 Python 3.6 中从嵌套字典中过滤所需的值
- c++ - 在 QuickFIX/C++ 中将 UtcTimeOnly 转换为毫秒
- c - 符号“_creat$NOCANCEL”中的“$”是什么意思?
- java - 如何显示以特定数字开头的所有值
- localization - 使用 XLIFF 本地化 TYPO3
- swift - 如何在 webview 中打开重定向页面?
- php - 如何使用 Laravel 5.8 在电子邮件中嵌入内联图像