简体   繁体   English

Scala 隐含值行为与列表和 Map “查找”

[英]Scala Implicit Value Behavior with List and Map “Lookups”

I saw the List behavior mentioned by a speaker in a Scala lecture video.我在 Scala 讲座视频中看到了演讲者提到的 List 行为。 Then thought I would try it with a Map.然后想我会用 Map 试试。 Also, seeing the same resolution of types via/through another type.此外,通过/通过另一种类型查看相同的类型分辨率。

I'm curious to how this resolution works?我很好奇这个决议是如何工作的? Was this intended on the part of the Scala language/compiler team?这是 Scala 语言/编译器团队的意图吗? Interested quirk that popped up?突然出现的感兴趣的怪癖? Will this function the same way in Dotty but with different syntax?这个 function 在 Dotty 中的方式是否相同但语法不同? Is there something special about the way List and Map are defined that says basically I can perform like a function and exchange one type for another? List 和 Map 的定义方式有什么特别之处吗?基本上说我可以像 function 一样执行并将一种类型交换为另一种类型?

Here is some sample code to illustrate what I am talking about:这是一些示例代码来说明我在说什么:

  // 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"

I guess because我猜是因为

implicitly[List[String] <:< (Int => String)]             // ok
implicitly[Map[Double, String] <:< (Double => String)]   // ok

so the following is valid所以以下是有效的

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM