简体   繁体   中英

Calling scala abstract classes with parameters and inner classes from Java

If I define a Scala class:

 class X(i:Int) {
   println (i)
 }

How do I use this class in Java code?

[EDIT] Actually, my problem is slightly more complicated

I have an abstract class

 abstract class X(i:Int) {
   println (i)
   def hello(s:String):Unit
 }

I need to use this in Java code. Is it possible to do it easily?

[EDIT2] Consider the following code

 object B {
    case class C(i:Int)
 }
 abstract class X(i:Int) {
   println (i)
   def hello(a:B.C):Unit
 }

In this case, the following java code gives an error in Netbeans IDE but builds fine:

 public class Y extends X  {
    public void hello(B.C c) {
       System.out.println("here");
    }
    public Y(int i) {
       super(i);
    }
 }

The error I get is:

hello(B.C) in Y cannot override hello(B.C) in X; overridden method is static, final

Netbeans 6.8, Scala 2.8.

As of now I think the only solution is to ignore the NB errors.

Here is an image showing the exact error(s) I get: 使用来自 java 的 scala 代码的 IDE 错误

The generated bytecode for your class will be identical to the Java definition:

abstract class X implements scala.ScalaObject {
  public X(int i) {
    System.out.println(i);
  }

  public abstract void hello(String s);

  //possibly other fields/methods mixed-in from ScalaObject
}

Use it exactly as you would for this equivalent Java; subclass and provide a concrete implementation of the hello method.

You need to pass the Scala library jar in the class path to compile any Java code extending a Scala class. For example:

dcs@ayanami:~/tmp$ cat X.scala
abstract class X(i:Int) {
   println (i)
   def hello(s:String):Unit
}

dcs@ayanami:~/tmp$ scalac X.scala
dcs@ayanami:~/tmp$ cat Y.java
public class Y extends X {
    public Y(int i) {
        super(i);
    }

    public void hello(String s) {
        System.out.println("Hello "+s);
    }
}
dcs@ayanami:~/tmp$ javac -cp .:/home/dcs/github/scala/dists/latest/lib/scala-library.jar Y.java

You should be able to call Scala code from Java (maybe with some name mangling and so on). What happens if you try the following?

X x = new X(23);

In more complicated cases you can use javap or similar tools to find out how the Scala code got translated. If nothing else works, you can still write some helper methods on Scala side to make access from Java side easier (eg when implicits are involved).

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