从List [Int]到List [Double]的隐式转换失败

时间:2012-12-27 20:49:50

标签: scala implicit-conversion

我是Scala新手,我注意到了一个我不理解的行为。当我执行此代码时,一切都很顺利:

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]

请您告诉我为什么在第二个列表中没有进行隐式转换?

2 个答案:

答案 0 :(得分:8)

没有从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> 

答案 1 :(得分:4)

明确地将List [Int]转换为List [Double]:

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