Java interoperability

Java is one of the most popular languages, and many programmers learn Java programming as their first entrance to the programming world. The popularity of Java has increased since its initial release back in 1995. Java has gained in popularity for many reasons. One of them is the design of its platform, such that any Java code will be compiled to bytecode, which in turn runs on the JVM. With this magnificent feature, Java language to be being written once and run anywhere. So, Java is a cross-platform language.

Also, Java has lots of support from its community and lots of packages that will help you get your idea up and running with the help of these packages. Then comes Scala, which has lots of features that Java lacks, such as type inference and optional semicolon, immutable collections built right into Scala core, and lots more features (addressed in Chapter 1, Introduction to Scala). Scala also runs on the JVM, just like Java.

Semicolon in Scala: Semicolons are exactly optional, and they are required when more lines of code should be written on a single line. That's probably the reason why the compiler doesn't complain if a semicolon is put at the end of a line: it is considered a piece of code followed by an empty piece of code that, coincidentally, lives on the same line.

As you can see that both Scala and Java run on the JVM, it makes sense to use them simultaneously in the same program without complaints from the compiler. Let's demonstrate this with an example. Consider the following Java code:

ArrayList<String> animals = new ArrayList<String>();
animals.add("cat");
animals.add("dog");
animals.add("rabbit");
for (String animal : animals) {
System.out.println(animal);
}

In order to write the same code in Scala, you can make use of Java packages. Let's translate the previous example into Scala with the help of using Java collections such as ArrayList:

import java.util.ArrayList
val animals = new ArrayList[String]
animals.add("cat")
animals.add("dog")
animals.add("rabbit")
for (animal <- animals) {
println(animal)
}

The previous mix applies for the standard packages of Java, but you want to use libraries that aren't packaged with the standard libraries of Java, or even want to use your own classes. Then, you need to make sure that they lie in the classpath.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.223.208