简体   繁体   中英

Calling a Java static method with generics from Scala

I have a Java method of the form

    public interface JavaInterface< T extends A >{
        static < T extends A > JavaInterface< T > callThis(){
         //I want to call this in scala

        }
    }

In Scala I write

val x = JavaInterface[SomeClass].callThis()

but I get an error telling me it "is not a value". How do I call that static method in Scala?

You want:

val x = JavaInterface.callThis[SomeClass]()

It's the method, not the type, that's parameterised for static methods.

The code you have now assumes JavaInterface is an object with a nilary apply method that returns another object with a callThis() method. For that, your code would have to look something like this (in Scala):

trait JavaInterface[T] {
  def callThis() = println("foobar")
}

object JavaInterface {
  def apply[T <: JavaInterface[T]] = new JavaInterface[T] {}
}

Since you are calling the callThis method on JavaInterface , you need to do JavaInterface.callThis[SomeClass]() instead, giving the type parameter to the method instead of the object (or Java interface) you're calling it on.

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