列表和映射的 Scala 隐式值行为 "Lookups"
Scala Implicit Value Behavior with List and Map "Lookups"
我在 Scala 讲座视频中看到一位演讲者提到的 List 行为。然后想我会用地图试试。此外,看到相同分辨率的类型 via/through 另一种类型。
我很好奇这个分辨率是如何工作的?这是 Scala language/compiler 团队的意图吗?突然出现的有趣怪癖?这个函数在 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 讲座视频中看到一位演讲者提到的 List 行为。然后想我会用地图试试。此外,看到相同分辨率的类型 via/through 另一种类型。
我很好奇这个分辨率是如何工作的?这是 Scala language/compiler 团队的意图吗?突然出现的有趣怪癖?这个函数在 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