scala - 带有列表和映射“查找”的 Scala 隐式值行为
问题描述
我在 Scala 讲座视频中看到了一位演讲者提到的 List 行为。然后想我会用地图试试。此外,通过/通过另一种类型查看相同的类型分辨率。
我很好奇这个决议是如何工作的?这是 Scala 语言/编译器团队的意图吗?突然出现的感兴趣的怪癖?这在 Dotty 中的功能是否相同但语法不同?List 和 Map 的定义方式有什么特别之处吗?基本上我可以像函数一样执行并将一种类型交换为另一种类型?
这是一些示例代码来说明我在说什么:
// I'm being verbose to stress the types
implicit val theList: List[String] = List("zero", "one", "two", "three")
implicit val theMap: Map[Double, String] = Map(1.1 -> "first", 2.1 -> "second")
def doExample(v: String): Unit = {
println(v)
}
doExample(1)
// prints "one"
doExample(1.1)
// prints "first"
解决方案
我猜是因为
implicitly[List[String] <:< (Int => String)] // ok
implicitly[Map[Double, String] <:< (Double => String)] // ok
所以以下是有效的
val x: Int => String = List("zero", "one", "two", "three")
val y: Double => String = Map(1.1 -> "first", 2.1 -> "second")
x(1)
y(1.1)
// val res5: String = one
// val res6: String = first
推荐阅读
- pytorch - ValueError:优化器得到一个空的参数列表
- php - 如何修复错误:SQLSTATE[42S02]: Base table or view not found: 114 6 表 'bbs_hnq.configs' 不存在(SQL: select * from `configs` limit 1)
- reactjs - 正确处理将摄像机流式传输到 HTML 视频元素的 React Hooks
- java - 使用 Executors.newCachedThreadPool 时 Java 常驻内存增长
- sql-server - SQL - WHERE 子句中的 AND 条件
- json - 如何从字符串中替换“并形成有效的Json
- python - 在匹配之前选择第一个日期,直到找到另一个匹配
- mysql - 如何加入没有记录的表?
- c++ - 如何使 cmake 支持 gcov
- machine-learning - (交叉)CNN 模型验证——何时引入测试数据?