3

I set up an android project to use java and scala. (android gradle scala plugin). Scala files are in src/scala directory and java files are in src/java directory.
Is there any way to use scala objects in java file?

Ashwin
  • 12,691
  • 31
  • 118
  • 190
  • 1
    Yes. Just use them. – Gábor Bakos Aug 14 '16 at 06:42
  • @GáborBakos : It doesn't work if I just use them. "It says cannot resolve symbol" – Ashwin Aug 22 '16 at 00:27
  • Have you also [added the Scala library dependency](https://github.com/saturday06/gradle-android-scala-plugin#3-add-scala-library-dependency)? (I assume yes because there were errors in Scala parts.) Or your problem is with using the Scala `object`s in the same project? – Gábor Bakos Aug 22 '16 at 06:28
  • @GáborBakos : ofcourse I have added the scala library dependency. I am trynig to use scala and java in the same project. I am trying to access scala classes from a java file (an android activity to be specific) – Ashwin Aug 24 '16 at 02:18
  • did you check: http://stackoverflow.com/questions/476111/scala-programming-for-android?rq=1 – piotrek1543 Aug 28 '16 at 11:33
  • maybe this not the right answer, but what about rewriting Scala to Kotlin, which is pretty similar programming language and also interoperatible – piotrek1543 Aug 28 '16 at 11:35

2 Answers2

0

The following works for me (though not Android, just JVM, Scala 2.11.8):

Scala:

object Simple {
  val s = 3
  def hello(sby: String) = s"Hello $sby"
}

Java:

//imports

public class X {
    public static void main(String[] args) {
        System.out.println(Simple$.MODULE$.hello("Ashwin"));
        int s = Simple$.MODULE$.s();
        System.out.println(s);
        //This also works for recent Scala versions,
        //though in this case you cannot use the singleton object references:
        Simple.s();
        Simple.hello("Ashwin");
    }
}
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
0

Here is a cool tutorial on how to integrate scala into android app.

Of course, you must integrate scala code into java like specific API (e.g. it can be organized with using annotation like BeanPropety in scala and etc). You can integrate java into scala and vise versa, but in my opinion the first approach is more useful.

See this article.

I also received useful tips from Chapter 17: Interacting with java in this book about scala.

chewpoclypse
  • 500
  • 5
  • 20
pacman
  • 797
  • 10
  • 28