Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java Libraries in Scala? [closed]

I have question I hope somebody guide me Can I use All Java Libraries such as Guava, Gson, Log4j, Spring, Hibernate & etc in Scala ??? for example can i convert below code to scala ?? (GUAVA library)

import com.google.common.base.Joiner;
public class mainJ {
    public static void main(String[] args) {
        String[] fantasyGenres = {"Space Opera", "Horror", "Magic realism", "Religion"};        
        String joined = Joiner.on(',').join(fantasyGenres);
        System.out.print(joined);
    }
}

I want choose SCALA as main programming language but i dont know Can I use Java libraries without limitation in scala or not ? Can anyone convert above code in scala ? thanks

like image 701
H F Avatar asked Oct 20 '25 03:10

H F


2 Answers

According to Scala FAQ (emphasis added):

The standard Scala backend is a Java VM. Scala classes are Java classes, and vice versa. You can call the methods of either language from methods in the other one. You can extend Java classes in Scala, and vice versa. The main limitation is that some Scala features do not have equivalents in Java, for example traits.

Do I need to convert Java data structures to Scala, and vice versa?

You do not have to convert Java data structures at all for using them in Scala. You can use them "as is". For instance, Scala classes can subclass Java classes, you can instantiate Java classes in Scala, you can access methods, fields (even if they are static), etc.

like image 71
Mateusz Avatar answered Oct 21 '25 16:10

Mateusz


As others pointed out, you can easily use Java classes in Scala. Gyro Gearless and maasg showed how can you use Scala's library to do Guava's work in your sample. You can use Guava as well obviously, here's how you can transform you sample to Scala more straightforwardly:

import com.google.common.base.Joiner
import scala.collection.JavaConverters._

object MainJ extends App {
  val fantasyGeneres = Array("Space Opera", "Horror", "Magic realism", "Religion")
  val joined = Joiner.on(',').join(fantasyGeneres.toIterable.asJava)
  println(joined)
}

Note that I used JavaConverters to convert Scala's Iterable to Java's version, but that's the only thing that can be considered as inconvenience here.

like image 28
Dmitry Kuskov Avatar answered Oct 21 '25 17:10

Dmitry Kuskov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!