简体   繁体   中英

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?

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 . Those views represent implicit conversions

在此处输入图片说明

So the only thing that means is that there's a conversion from IndexedSeq to Array .

View bound works for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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