【发布时间】:2017-05-16 21:55:54
【问题描述】:
考虑以下 REPL 会话:
@ def test[C[X] <: TraversableOnce[X]](implicit cbf: CanBuildFrom[C[Int], Int, C[Int]]) = cbf()
defined function test
@ test[List]
res32: collection.mutable.Builder[Int, List[Int]] = ListBuffer()
@ def test[C[X] <: TraversableOnce[X]] = implicitly[CanBuildFrom[C[Int], Int, C[Int]]]
cmd33.sc:1: Cannot construct a collection of type C[Int] with elements of type Int based on a collection of type C[Int].
def test[C[X] <: TraversableOnce[X]] = implicitly[CanBuildFrom[C[Int], Int, C[Int]]]
^
Compilation Failed
test 函数的第一个定义编译并工作,而第二个不编译。它们之间的唯一区别是CanBuildFrom 实例的获取方式。在第一种情况下,它被声明为隐式参数,要求编译器找到一个。在第二种情况下,它是通过 implicitly 函数调用的,理论上,它在隐式搜索范围方面的行为应该相同。是什么导致了这种行为?
【问题讨论】: