我说奇怪是因为下面的代码编译了很长时间没有提示也没有评论。
val depth = dbStuff.lookupSomeInt(blah, blah)
for (x: Int <- 0 to depth) {
doStuffWith(x).orNot
}
然而今天它没有在我的一台机器上编译(同时还在另一台机器上编译)
这是错误:
[error] /Users/SomeOne/SomePath/SomeFile.scala:415: type mismatch;
[error] found : Int
[error] required: scala.collection.generic.CanBuildFrom[Nothing,String,?]
[error] for (x: Int <- 0 to depth) {
[error] ^
[error] one error found
在食物链的上游,我确实添加了一个 val:
protected implicit val columnOrderByList = Seq.empty[Seq[String]]
这是我知道的唯一更改,并且在添加后立即发生错误。
修复似乎是:
for (x: Int <- Range(0, depth, 1)) {
doStuffWith(x).orNot
}
它拒绝了所有其他使“范围”工作的尝试:例如
(0 to depth)
在括号等中讨厌说出来负载但错误之类的吓到我的废话。如果这是 500 个编译错误而不是 1 个,会发生什么?或者如果“修复”没有变得不言而喻怎么办?更糟糕的是,如果根本原因也不是不言而喻的,因此甚至不可能退出呢?
我敢肯定,有些天才确切地知道这里发生了什么以及为什么,但我不知道如何找出(如要遵循的路径)以在我的孤独中解决这个问题……
欢迎光!
确认:我删除了
protected implicit val columnOrderByList
并且原始代码编译没有问题——我把它放回去,我得到了记录的错误。在食物链上,我的意思是val
所在的类被具有此编译错误的类继承,因此 val
将在范围内。
最佳答案
这只是许多隐式转换在范围内时可能发生的问题之一。
scala> 0 to 3
res0: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3)
相当于
scala> intWrapper(0) to 3
res1: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3)
然而,
scala> implicit val s: Seq[Seq[String]] = null
s: Seq[Seq[String]] = null
scala> 0 to 3
<console>:12: error: type mismatch;
found : Int(3)
required: scala.collection.generic.CanBuildFrom[Nothing,String,?]
0 to 3
^
相当于
scala> s(0) to 3
<console>:12: error: type mismatch;
found : Int(3)
required: scala.collection.generic.CanBuildFrom[Nothing,String,?]
s(0) to 3
^
scala> s.apply(0) to 3
<console>:12: error: type mismatch;
found : Int(3)
required: scala.collection.generic.CanBuildFrom[Nothing,String,?]
s.apply(0) to 3
^
您新引入的隐式值比预定义的值具有更高的偏好,因此它被选中。通常,这应该不是问题,但在这种情况下
Seq
定义一个方法to
,它可以将集合转换为不同类型的集合。其完整的signature是 def to[Col[_]](implicit cbf: CanBuildFrom[Nothing, A, Col[A]]): Col[A]
,它解释了有关预期 CanBuildFrom
的错误消息.演讲:尽可能减少隐含的范围。
关于scala - for 循环和范围 : found :Int required: scala. collection.generic.CanBuildFrom[Nothing,String,?] 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31233850/