I wrote a method that accepts objects of all subclasses of Seq[String]. Unfortunately it won’t accept an object of the type Array[String]. Is Array[String] not a subclass of Seq[String]?
scala> def test[T <: Seq[String]](x: T) = {}
test: [T <: Seq[String]](x: T)Unit
scala> val data = "This is a test string"
data: java.lang.String = This is a test string
scala> test(data.split(" "))
<console>:10: error: inferred type arguments [Array[java.lang.String]] do not conform to method test's type parameter bounds [T <: Seq[String]]
test(data.split(" "))
No,
Array[String]translates to regular JVM arrays, like the ones you see in Java:String[].The reason why you see all the operations on
Array[String]that you see on other ScalaSeqcollections is that there is an implicit conversion fromArray[T]toArrayOps[T].Do this:
This is called a view bound. It means that
Tshould either be a subtype ofSeq[String]or there should exist an implicit conversion in scope which convertsTinto aSeq[String]. Behind the scenes, the compiler actually adds an implicit parameter totest, so this method becomes:This
implicit evidence$1is the function which now acts as the implicit conversion fromTtoSeq[String]within the body of the method.