【问题标题】:Unable to override java generic function with scala parameterized type无法使用 scala 参数化类型覆盖 java 泛型函数
【发布时间】:2018-06-20 16:11:06
【问题描述】:

我收到错误 - 方法读取的类型不兼容;当我尝试使用 Scala 参数化类型覆盖 java 泛型函数名时。

这是我试图重写的 java 抽象函数。

    public abstract class SRType{

    //Other abstract functions

    public abstract <T> T read()throws IOException;
}

我在 scala 中通过以下方式使用这个抽象类 -

abstract class SRType(val name: String) extends org.xyz.SRType {

  // to convert to spark
  val toSparkType: DataType
}

abstract class SRCollection(name: String, isTop: Boolean) extends SRType(name)

这是试图覆盖它的 scala 函数。

    case class SRSTLString(override val name: String,
                       b: TBranch,
                       isTop: Boolean) 
  extends SRCollection(name, isTop) {

  //Other functions

  override def read[T]: String = {
    //Code
    }

}

错误代码-

[error] overriding method read in class SRType of type [T]()T;
[error]  method read has incompatible type
[error]  override def read[T]: String = {

任何建议将不胜感激。

【问题讨论】:

  • 试试这个:覆盖 def read[String]: String = { // 代码 }
  • 刚刚试了一下,还是一样的错误。
  • override def read[String](): String 应该可以工作
  • 不工作。它显示完全相同的错误。

标签: java scala generics


【解决方案1】:

你不能那样做。方法签名需要一个泛型类型参数,您不能用String 或任何类型替换它。类型参数必须保持通用,因为这是抽象类所要求的方法签名。

您可以做的是将泛型类型参数移至类级别,并为继承类型显式声明它:

public abstract class Foo<T> {
    public abstract T read() throws IOException;
}

然后:

class Bar extends Foo[String] {
  override def read(): String = "foo"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2012-01-08
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多