簡體   English   中英

類型擦除在哪里發生,並且避免這種情況的安全方法是什么?

[英]Where does the type erasure happen and what is a safe way to stay away from this?

def decode(l: List[(Int, Symbol)]) : List[Symbol] = {
    def foo(r : Int, s: Symbol):List[Symbol] = r match {
      case 0 => Nil
      case x: Int => s::foo(r-1,s)
    }

    l match {
      case Nil => Nil
      case h::tail => foo(h._1 , h._2 ) :+ decode(tail)
    }

}

在這里,我得到了一個編譯錯誤“ scala:類型不匹配;找到了:List [Object]必需:List [Symbol] case h :: tail => foo(h._1:Int,h._2:Symbol):+ decode(tail )“

這不是類型擦除,簡單的類型不匹配:

foo(h._1 , h._2 ) :+ decode(tail)

foo的結果是List[Symbol] ,解碼的結果是List[Symbol] 現在你試圖把List里面List ,沒有surprize該編譯器認為,只有這樣,才能存儲ListSymbols內部List是給后來列表對象(任意)類型。

您很可能只想合並兩個列表:

foo(h._1 , h._2 ) ++ decode(tail)

暫無
暫無

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

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