簡體   English   中英

Scala 隱含值行為與列表和 Map “查找”

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

我在 Scala 講座視頻中看到了演講者提到的 List 行為。 然后想我會用 Map 試試。 此外,通過/通過另一種類型查看相同的類型分辨率。

我很好奇這個決議是如何工作的? 這是 Scala 語言/編譯器團隊的意圖嗎? 突然出現的感興趣的怪癖? 這個 function 在 Dotty 中的方式是否相同但語法不同? List 和 Map 的定義方式有什么特別之處嗎?基本上說我可以像 function 一樣執行並將一種類型交換為另一種類型?

這是一些示例代碼來說明我在說什么:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM