简体   繁体   中英

How to call a scala.Function2 with a scala.Int parameter from Java

I'm trying to call a scala.Function2 from java:

static public String foo(scala.Function2<String, scala.Int, String> bar) {
    return "Hello " + bar.apply("World", 2);
}

But the compilation fails with incompatible types: int cannot be converted to scala.Int on the second parameter in the call to bar.apply .

new scala.Int(2) , scala.Int.unbox(2) , scala.Int.box(2) or creating a scala converter function like object Helper { def convert(i:Int):Int = i } also don't work.

How do I create a scala.Int that I can pass to bar() in java?

The usual answer is that you want your Scala function "specialized" for the int parameter.

Your adapter method should take (String, Int) and forward to the function, which is not the specialized signature because of the nefarious String.

Ordinarily, unspecialized signatures unbox and forward to the specialized method.

Showing ordinary passing an int:

passint $ cat p.scala

package p

class C {
  def f(): (Int => String) = (i => i.toString * i)
}
passint $ cat p/Main.java 

package p;

public class Main {
    public static void main(String... args) {
        C c = new C();
        System.out.println(c.f().apply(42));
    }
}
passint $ scalac p.scala
passint $ javac -cp .:/Users/andrew/scala-2.12.6/lib/scala-library.jar p/Main.java
passint $ java -cp .:/Users/andrew/scala-2.12.6/lib/scala-library.jar p.Main
424242424242424242424242424242424242424242424242424242424242424242424242424242424242
passint $ 

scala.Int is just not a type that should ever appear in Java code, it exists for Scala compiler's internal purposes. Any uses of Int as a type in Scala code should become either int or java.lang.Integer after compilation, so it isn't useful for interoperation between Scala and Java.

For some (not all) special types like scala.Int there is a corresponding Java .class file, so it's possible to use them from Java, but so far as I know it's never useful (except perhaps some of the static methods).

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