简体   繁体   English

用于隐式转换集合的Scala类型方差

[英]Scala Type Variance for Implicit Conversion of Collection

How come this doesn't work? 为什么这不起作用?

implicit class ImplicitHelper[T <: IndexedSeq[String]](i: T) = {
    def bar() = ???
}

val foo: Array[String] = ???
foo.bar // no implicit conversion …

doesn't Array implement? 数组没有实现吗? IndexedSeq in the Scala unified collection hierarchy? Scala统一集合层次结构中的IndexedSeq?

Update: As a few users pointed out, the dotted line represents not an implementation but a implicit conversion. 更新:正如一些用户指出的那样,虚线不是实现,而是隐式转换。 thus the proper way is to use view bounds instead of type bounds per answers below 因此正确的方法是使用视图范围而不是下面每个答案的类型范围

在此处输入图片说明

The non contiguous line represents a view, not a direct hierarchy: 不连续的线表示视图,而不是直接的层次结构:

final class Array[T](_length: Int) extends java.io.Serializable with java.lang.Cloneable

As you can see array doesn't extend IndexedSeq . 如您所见,数组不会扩展IndexedSeq Those views represent implicit conversions 这些视图表示隐式转换

在此处输入图片说明

So the only thing that means is that there's a conversion from IndexedSeq to Array . 因此,这唯一的意思是从IndexedSeqArray都有转换。

View bound works for me: 查看绑定作品对我来说:

implicit class ImplicitHelper[T <% IndexedSeq[String]](i: T) {
    def bar() = ???
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM