简体   繁体   中英

Scala Implicit Value Behavior with List and Map “Lookups”

I saw the List behavior mentioned by a speaker in a Scala lecture video. Then thought I would try it with a 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? Interested quirk that popped up? Will this function the same way in Dotty but with different syntax? 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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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