我正在嘗試使用 Int 和 Long 的可變串列多載建構式,它提到該方法已經定義。我需要updateList要么mutable.MutableList[Int]mutable.MutableList[Long]
object PercentileDistribution {
def apply(updateList: mutable.MutableList[Int], percentileDistribution: PercentileDistribution): PercentileDistribution = {
updateList.foreach { x =>
percentileDistribution.update(x)
}
percentileDistribution
}
def apply(updateList: mutable.MutableList[Long], percentileDistribution: PercentileDistribution): PercentileDistribution = {
updateList.foreach { x =>
percentileDistribution.update(x)
}
percentileDistribution
}
}
作為 scala 的新手,我遇到了一些問題,感謝您的幫助。
uj5u.com熱心網友回復:
該錯誤顯然是指代碼中發生的向上轉換。AnInt可以表示為 aLong因此您基本上撰寫了相同的方法,其中一個方法引數是另一個 apply 方法的引數的向上轉換版本。
您可以簡單地使用具有MutableList[Long]型別的 apply 方法并洗掉帶有Int.
按照官方 scala 檔案中的此檔案,您將對型別在 Scala 中的行為方式有一個很好的了解
uj5u.com熱心網友回復:
該錯誤是指型別擦除。另一個答案錯誤地指出它與強制轉換有關(盡管型別擦除可能導致與強制轉換相關的問題)。
在 Scala REPL 會話中完成的一個簡單示例:
scala> class Foo {
| def bar(list: List[Int]) = "ints"
| def bar(list: List[String]) = "strings"
| }
<console>:12: error: double definition:
def bar(list: List[Int]): String at line 11 and
def bar(list: List[String]): String at line 12
have same type after erasure: (list: List)String
def bar(list: List[String]) = "strings"
^
這里的訊息是說這兩種bar方法都會有一個型別簽名,就像def bar(list: List): String編譯的輸出一樣;型別擦除正在消除[Int]和[String]引數,使這兩種方法無法區分。如果您在 JVM 上運行代碼,這是您必須忍受的煩惱。
我推薦的解決方法是通過名稱來區分方法,例如,apply您可以將其稱為forIntsand forLongs。
另請注意,型別擦除會導致另一個問題:
scala> List(1,2,3).isInstanceOf[List[String]]
<console>:11: warning: fruitless type test: a value of type List[Int] cannot also be a List[String] (the underlying of List[String]) (but still might match its erasure)
List(1,2,3).isInstanceOf[List[String]]
^
res5: Boolean = true
和
scala> List(1, 2, 3) match {
| case l: List[String] => l // you'd think this shouldn't match, but it does
| }
<console>:12: warning: fruitless type test: a value of type List[Int] cannot also be a List[String] (the underlying of List[String]) (but still might match its erasure)
case l: List[String] => l // you'd think this shouldn't match, but it does
^
res2: List[Int] with List[String] = List(1, 2, 3)
scala> res2.head
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
... 33 elided
由于在編譯的位元組碼中,List[Int]并且List[String]都只表示為List,運行時實際上無法區分兩者,因此isInstanceOf檢查可能會提供錯誤的答案,可能會導致 ClassCastExceptions 因為它試圖將 aInt視為String.
在您的情況下,您可能會僥幸成功,因為將Inta 轉換為 a是安全的Long,但最好完全避免未經檢查的轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/474432.html
標籤:斯卡拉
上一篇:如何在Kotlin中將scala.collection.mutable.Map轉換為scala.collection.immutable.Map?
