我在 Scala 讲座视频中看到一位演讲者提到的 List 行为。然后我想我可以用 map 来尝试一下。此外,通过/通过另一种类型查看类型的相同分辨率。
我很好奇这个决议是如何运作的?这是 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
关于Scala 列表和映射的隐式值行为 "Lookups",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62457201/