Cannot invoke overloaded constructor in Scala

My code is as follows:

val people = Array(Array("John", "25"), Array("Mary", "22")) val headers = Seq("Name", "Age") val myTable = new Table(people, headers) 

I get this syntax error:

 overloaded method constructor Table with alternatives: (rows: Int,columns: Int)scala.swing.Table <and> (rowData: Array[Array[Any]],columnNames: Seq[_])scala.swing.Table cannot be applied to (Array [Array[java.lang.String]], Seq[java.lang.String]) 

I do not understand why the second alternative is not used. Are there any differences between "Any" and "_" that turned me off?

+6
source share
2 answers

As Kim has already said, you need to make your array covariant in element type, because Scala Arras are not covariant like Java / C #.

This code will make it work, for example:

 class Table[+T](rowData: Array[Array[T]],columnNames: Seq[_]) 

It just tells the compiler that T should be covariant (is it like Java ? extends T or C # out T ).

If you need more control over which types are allowed and which are not, you can also use:

 class Table[T <: Any](rowData: Array[Array[T]],columnNames: Seq[_]) 

This will tell the compiler that T can be any subtype of Any (which can be changed from Any to the required class, such as CharSequence in your example).

Both options work the same in this scenario:

 scala> val people = Array(Array("John", "25"), Array("Mary", "22")) people: Array[Array[java.lang.String]] = Array(Array(John, 25), Array(Mary, 22)) scala> val headers = Seq("Name", "Age") headers: Seq[java.lang.String] = List(Name, Age) scala> val myTable = new Table(people, headers) myTable: Table[java.lang.String] = Table@350204ce 

Edit: If the class in question is not in your control, declare the type you want explicitly:

 val people: Array[Array[Any]] = Array(Array("John", "25"), Array("Mary", "22")) 

Update

This is the source code:

 // TODO: use IndexedSeq[_ <: IndexedSeq[Any]], see ticket [#2005][1] def this(rowData: Array[Array[Any]], columnNames: Seq[_]) = { 

Interestingly, someone forgot to remove the workaround because # 2005 has been fixed since May 2011 ...

+5
source

Array[Array[String]] not a subtype of Array[Array[Any]] , because the array type parameter is not covariant. You should read co-, contra- and invariance . This should fix this:

 val people = Array(Array("John", "25"), Array("Mary", "22")).asInstanceOf[Array[Array[Any]] 
+3
source

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


All Articles