首页 > 解决方案 > 带有列表和映射“查找”的 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"

标签: scalaimplicit-conversionimplicit

解决方案


我猜是因为

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 

推荐阅读