Scala type inference: cannot derive IndexedSeq [T] from array [T]

In Scala 2.11.2, the following minimal example compiles only when using a type in Array[String] :

 object Foo { def fromList(list: List[String]): Foo = new Foo(list.toArray : Array[String]) } class Foo(source: IndexedSeq[String]) 

If I remove the type assignment in fromList , it will not be able to compile with the following error:

 Error:(48, 56) polymorphic expression cannot be instantiated to expected type; found : [B >: String]Array[B] required: IndexedSeq[String] def fromList(list: List[String]): Foo = new Foo(list.toArray) ^ 

Why can't the compiler specify Array[String] here? Or should this problem have something to do with the implicit conversion from Array to IndexedSeq ?

+6
source share
1 answer

The problem is that the .toArray method returns an array of some type B , which is a superclass of T in List[T] . This allows you to use list.toArray on List[Bar] where Array[Foo] is required if Bar extends Foo .

Yes, the real reason this doesn't work is because the compiler is trying to figure out which B use, as well as how to get to IndexedSeq . It looks like it is trying to resolve the IndexedSeq[String] requirement, but B only guaranteed to String or the superclass from String ; hence a mistake.

This is my favorite job:

 def fromList(list: List[String]): Foo = new Foo(list.toArray[String]) 
+4
source

Source: https://habr.com/ru/post/977544/


All Articles