无法在 Scala 中调用重载的构造函数 [英] Can't call an overloaded constructor in Scala

查看:55
本文介绍了无法在 Scala 中调用重载的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

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

我收到此语法错误:

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])

我不明白为什么不使用第二种选择.Any"和_"之间是否有区别让我在这里绊倒?

I don't see why the second alternative isn't used. Is there a distinction between "Any" and "_" that's tripping me up here?

推荐答案

正如 Kim 已经说过的,你需要在他的元素类型中使你的数组​​协变,因为 Scala 的 Arras 不像 Java/C# 那样协变.

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

此代码将使其工作例如:

This code will make it work for instance:

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

这只是告诉编译器 T 应该是协变的(这类似于 Java 的 ? extends T 或 C# 的 out T).

This just tells the compiler that T should be covariant (this is similar to Java's ? extends T or C#'s out T).

如果您需要更多地控制允许和不允许的类型,您还可以使用:

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

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

这将告诉编译器 T 可以是 Any 的任何子类型(可以从 Any 更改为您需要的类,就像你的例子中的 CharSequence).

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

在这种情况下,两种情况的工作方式相同:

Both cases 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

如果有问题的类不在您的控制范围内,请像这样明确声明您想要的类型:

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

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

<小时>

更新

这是有问题的源代码:

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

我想知道是否有人忘记删除解决方法,因为自 2011 年 5 月以来 #2005 已修复......

I wonder if someone forgot to remove the workaround, because #2005 is fixed since May 2011 ...

这篇关于无法在 Scala 中调用重载的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆