本文介绍了从List [Int]到List [Double]的隐式转换失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Scala新手,但是我注意到一种我不了解的行为.当我执行此代码时,一切都会顺利进行:
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
我得到一个错误
<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?
推荐答案
没有定义从List [Int]到List [Double]的隐式转换,尽管如果您确实想要一个,也可以创建一个.请参阅以下内容:
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>
这篇关于从List [Int]到List [Double]的隐式转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!