I am new to Scala. I am only able to write basic code thus far, but I want to start using it more concretely, rather than just learning theory.
Let's say I have the following Java code in HelloWorld.java:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }
What would the code be to invoke it from Scala?
Scala is designed to work smoothly with Java and Java libraries like JMSL. This is clearly evident in how Scala picks up the same CLASSPATH environment variable Java uses, so if the Java library you wish to use is already there in the CLASSPATH, then you're good to go.
When you're writing Scala code and need to use a Java collection class, you can just use the class as-is. However, if you want to use the class in a Scala for loop, or want to take advantage of the higher-order functions on the Scala collections classes, you'll want to convert the Java collection to a Scala collection.
Is it possible to mix Scala and Java code? Yes, there is the ability to mix both types of code. It is possible to create an SBT project, put Scala code in src/main/scala and java code in src/main/java in the same project and make it work.
In your example, you just have a main, not a function you would necessarily call from somewhere else. But let's said you did have a function like
package com.example.hello; public class HelloWorld { public static void sayHello() { System.out.println("Hello, world!"); } }
(I also added a package for your example, for completeness). Then in your Scala code, you could do:
import com.example.hello._ object GreetWorld extends App { (0 until 10).foreach { HelloWorld.sayHello() } }
to say hello using the Java function 10 times in Scala. The ._
in the import
imports all members of the package, or alternatively you could just import com.example.hello.HelloWorld
. You could even import the method itself with import com.example.hello.HelloWorld.sayHello
so that you don't need to reference the HelloWorld
object in your code.
Both languages compile into JVM bytecode, so calling Java code from Scala is very simple, although calling Scala from Java can be trickier if there are are implicit parameters involved.
The equivalent code would be:
object HelloWorld extends App { println("Hello, world!") }
If you saved that code in a file called HelloWorld.scala
then you could compile and run it like so:
$ scalac HelloWorld.scala $ scala HelloWorld Hello, world!
Or if you are working in the REPL:
scala> :paste // Entering paste mode (ctrl-D to finish) object HelloWorld extends App { println("Hello, world!") } // Exiting paste mode, now interpreting. defined module HelloWorld scala> HelloWorld.main(Array.empty[String]) Hello, world!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With