簡體   English   中英

從List [Int]到List [Double]的隱式轉換失敗

[英]Implicit conversion from List[Int] to List[Double] fails

我是斯卡拉新手,我注意到了一個我不理解的行為。 當我執行此代碼時,一切都很順利:

val lD: List[Double] = List(1, 2, 3)

但是當我執行這個時:

val lI = List(1, 2, 3)
val lD: List[Double] = lI

我收到一個錯誤

<console>:11: error: type mismatch;
 found   : List[Int]
 required: List[Double]

請您告訴我為什么在第二個列表中沒有進行隱式轉換?

從List [Int]到List [Double]沒有定義隱式轉換,但如果你真的想要一個,你可以制作一個。 請參閱以下內容:

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val i = 1
i: Int = 1

scala> val d: Double = i
d: Double = 1.0

scala> val il = List(1,2,3,4)
il: List[Int] = List(1, 2, 3, 4)

scala> val dl: List[Double] = il
<console>:8: error: type mismatch;
 found   : List[Int]
 required: List[Double]
       val dl: List[Double] = il
                              ^

scala> object il2dl { implicit def intlist2dlist(il: List[Int]): List[Double] = il.map(_.toDouble) }
defined module il2dl

scala> import il2dl._
import il2dl._

scala> val dl: List[Double] = il
dl: List[Double] = List(1.0, 2.0, 3.0, 4.0)

scala> 

只需將List [Int]轉換為List [Double]:

val lI = List(1, 2, 3)
val lD: List[Double] = lI map (_.toDouble)

暫無
暫無

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

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