How can collections use implicit conversions on el

2019-02-17 22:35发布

While working on this question, I came up with the following issue. Consider two method definitions:

def foo[T <: Ordered[T]](s : Seq[T]) = s.sorted

def foo[T <% Ordered[T]](s : Seq[T]) = s.sorted

The first one compiles, the second does not. The compiler does not figure out that it can use the asserted implicit conversion to get an Ordering. If we help a bit, it works:

def foo[T <% Ordered[T]](s : Seq[T]) = s.sortWith(_<=_)

While compiling the anonymous function the compiler applies the implicit conversion to find method <=, everything is fine.

I do not have another example, but can imagine similar issues to happen with other functions on collections that require elements to have certain properties, if those can only be asserted via conversion.

Is there a particular reason why the compiler is restricted this way? Is there no general way to resolve such issues? (Here it seems easy.) Is there a workaround, e.g. another implicit conversion that translates the property on Key[T] to T?

(Note that the last idea can be problematic if a concrete value for T ends up having the property; we then get an ambiguous situation).

2条回答
我命由我不由天
2楼-- · 2019-02-17 23:12
scala> implicit def ordering[T <% Ordered[T]] = new Ordering[T]{def compare(x: T, y: T) = x compare y}
ordering: [T](implicit evidence$1: (T) => Ordered[T])java.lang.Object with Ordering[T]

scala> def foo[T <% Ordered[T]](s : Seq[T]) = s.sorted
foo: [T](s: Seq[T])(implicit evidence$1: (T) => Ordered[T])Seq[T]
查看更多
Fickle 薄情
3楼-- · 2019-02-17 23:12
% scala29
Welcome to Scala version 2.9.0.r24168-b20110202012927 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def foo[T <% Ordered[T]](s : Seq[T]) = s.sorted
foo: [T](s: Seq[T])(implicit evidence$1: (T) => Ordered[T])Seq[T]

scala>

By the way, re "here it seems easy", it wasn't. Implicits like these enjoy diverging and they were pretty determined.

查看更多
登录 后发表回答