好吧,但你不会相信的。打开-Yinfer-debug
你的CanBuildFrom
反例,
[search] $line14.$read.$iw.$iw.build[scala.this.Int, Seq[scala.this.Int]](1, 2) with pt=generic.this.CanBuildFrom[scala.this.Nothing,scala.this.Int,Seq[scala.this.Int]] in module class $iw, eligible:
fallbackStringCanBuildFrom: [T]=> generic.this.CanBuildFrom[String,T,immutable.this.IndexedSeq[T]]
[solve types] solving for T in ?T
inferExprInstance {
tree scala.this.Predef.fallbackStringCanBuildFrom[T]
tree.tpe generic.this.CanBuildFrom[String,T,immutable.this.IndexedSeq[T]]
tparams type T
pt generic.this.CanBuildFrom[scala.this.Nothing,scala.this.Int,Seq[scala.this.Int]]
targs scala.this.Int
tvars =?scala.this.Int
}
[search] considering no tparams (pt contains no tvars) trying generic.this.CanBuildFrom[String,scala.this.Int,immutable.this.IndexedSeq[scala.this.Int]] against pt=generic.this.CanBuildFrom[scala.this.Nothing,scala.this.Int,Seq[scala.this.Int]]
[success] found SearchResult(scala.this.Predef.fallbackStringCanBuildFrom[scala.this.Int], ) for pt generic.this.CanBuildFrom[scala.this.Nothing,scala.this.Int,Seq[scala.this.Int]]
[infer implicit] inferred SearchResult(scala.this.Predef.fallbackStringCanBuildFrom[scala.this.Int], )
事实上,
implicit def fallbackStringCanBuildFrom[T]: CanBuildFrom[String, T, immutable.IndexedSeq[T]] =
new CanBuildFrom[String, T, immutable.IndexedSeq[T]] {
def apply(from: String) = immutable.IndexedSeq.newBuilder[T]
def apply() = immutable.IndexedSeq.newBuilder[T]
}
你是什么意思,你的 Iterable 不是字符串?
trait CanBuildFrom[-From, -Elem, +To]
这就是推断 Nothing 或 Any 的坏处。
编辑:对不起,我说错了,我看到你没有明确地告诉它。
更新:
由于 CBF 在 中是逆变的From
,因此来自 的 CBFString
充当来自 的 CBF Nothing
。
scala> typeOf[CanBuildFrom[Nothing,Int,Seq[Int]]] <:< typeOf[CanBuildFrom[String,Int,Seq[Int]]]
res0: Boolean = false
scala> typeOf[CanBuildFrom[String,Int,Seq[Int]]] <:< typeOf[CanBuildFrom[Nothing,Int,Seq[Int]]]
res1: Boolean = true
例如,如果您需要从 构建immutable.Map
,您需要一个 CBF fromcollection.Map
来工作。
正如其他人评论的那样,这对于Nothing
. 但是你得到了你所要求的。也就是说,您未指定,这意味着您不太介意返回的内容,Vector 或其他内容。