Everybody knows about Java and Scala, but how much interoperability is there between C++ and Scala. Can classes from one be be used by the other, for example?
-
Java and Scala programs both run on the JVM; C++ produces platform-dependent machine code. What are you asking? Are you looking for a sort of native interface a la JNI? – Kerrek SB Aug 12 '11 at 08:55
-
Yes, JNI is what I was thinking of. Just a way to call classes from one language into the other. – Henry Henrinson Aug 12 '11 at 13:20
-
ONce you have exposed your C++ classes in Java using JNI, it's trivial to use them from Scala. (Just as you would use _any_ Java classes from Scala.) – Mohan Oct 08 '18 at 11:54
3 Answers
It's not that simple at all. Java and Scala work on the same virtual machine and scala has been designed to work well with java.
C++ generates native code, and even each compiler has its own way to generate that native code. That means that some class compiled with Visual Studio won't interact easily with another class compiled with gcc.
If you need to interact with C++, you need to use some glue with JNI http://en.wikipedia.org/wiki/Java_Native_Interface. I believe it should be straightfoward to use it with scala. You can make interaction somewhat more comfortable using Swig http://www.swig.org/

- 37,300
- 12
- 75
- 90

- 9,601
- 3
- 34
- 50
-
3For binding native libraries that are written in C or Fortran, I'm a fan of JNA (Java Native Access). It's a pure Java solution that requires much less boilderplate than JNI. However, for C++, it seems that JNI is the better option according: http://stackoverflow.com/questions/1556421/use-jni-instead-of-jna-to-call-native-code . JNAerator, suggestion by thoredge is another one to look into, and also generates binding for BridJ which might fill in some gaps of JNA. – Kipton Barros Aug 12 '11 at 14:52
To make this kind of interoperability even possible, both implementations must compile for the same intermediate language (i.e. Java bytecode, .Net IL, LLVM). Scala.Net and C++/CLI is the closest combination — both produce code for .Net. But even then it's not that simple, as a class in Scala and a class in C++ stand for slightly different things.
Typically, Scala stands for Scala for Java VM, and C++ stands for C++ for native code, so general answer should be “not much more than between any other two randomly picked languages”.

- 24,039
- 5
- 57
- 72
-
C++/CLI doesn't produce pure IL code, it produces mixed native and managed code in general - that's the whole point of it, compared to, say, C#. So at best I'd say that you could hope for code reuse between Scala.NET and C#... – Kerrek SB Aug 12 '11 at 09:34