使用以下 MRE,我希望得到以下輸出:
$ scala mre.scala
1
object Main {
def main(args: Array[String]): Unit = {
implicit val thing = List[String]().map(_.to(List))
for (x <- 1 to 1) {
println(x)
}
}
}
但是我得到的是以下內容
$ scala mre.scala
mre.scala:4: error: type mismatch;
found : Int(1)
required: scala.collection.Factory[Char,?]
for (x <- 1 to 1) {
如果我洗掉 theimplicit或 the.map(_.to(List))那么它會按預期作業。
這到底是怎么回事?我什至不知道從哪里開始。
$ scala --version
Scala code runner version 2.13.7 -- Copyright 2002-2021, LAMP/EPFL and Lightbend, Inc.
uj5u.com熱心網友回復:
一個有根據的猜測(比如 99% 的確定性):任何集合擴展 ( Partial)Function因此,通過使集合隱式,您提供了隱式轉換(因為任何一元implicit defOR 隱式函式都是隱式轉換):
// this
implicit val thing = List[String]().map(_.to(List))
// implies this
implicit def intToCharList(idx: Int): List[Char]] = thing(idx)
然后在這里:
1 to 1
你有歧義:它可能是:
- 擴展方法
.to(Int)上Int - 通常的方法
.to(CollectionType)在List(自斯卡拉2.13)之后Int將隱式轉換
如果編譯器選擇后者,那么你有類似
thing(1).to(1) // .to expects collection factory and got 1 instead
這會觸發您看到的錯誤。它可能會選擇后者,因為您在同一范圍內宣告了richInt隱式轉換,而在LowPriorityImplicitin 中宣告了隱式轉換scala.Predef,因此 Scala 會更喜歡您的。
在 Scala 3 中,隱式轉換是 的一個子型別,Function所以這個問題不會發生。在 Scala 2 中,我只能強烈建議不要將任何集合設為隱式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381439.html
標籤:斯卡拉
