简体   繁体   中英

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

I am a Scala newbie and I've noticed a behaviour I do not understand. When I execute this code everything goes just fine:

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

However when I execute this one:

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

I get an error

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

May you please give me a clue why an implicit conversion does not take place in the second listing?

There's no implicit conversion defined from List[Int] to List[Double], although if you really want one you can make one. See the following:

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> 

Just transform List[Int] to List[Double] explicitly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM