简体   繁体   中英

Unable to override java generic function with scala parameterized type

I am getting the error - Method read has incompatible type ; when I try to override a java generic function name with a Scala parameterized type.

This is the java abstract function I am trying to override.

    public abstract class SRType{

    //Other abstract functions

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

I am using this abstract class in scala in the following way -

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)

And this is the scala function which is trying to override it.

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

  //Other functions

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

}

Error code -

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

Any suggestions would be greatly appreciated.

You can't do that. The method signature requires a generic type parameter, you cannot replace it with String or any type for that matter. The type parameter must remain generic as that is what the method signature demanded by the abstract class.

What you can do is move the generic type parameter to the class level and have it explicitly declared for inheriting types:

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

And then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM