I am a 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.
Lets 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 equivalent Scala code be?
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
(I also added a package for your example, for completeness). Then in your Scala code, you could do:
to say hello using the Java function 10 times in Scala. The
._
in theimport
imports all members of the package, or alternatively you could justimport com.example.hello.HelloWorld
. You could even import the method itself withimport com.example.hello.HelloWorld.sayHello
so that you don't need to reference theHelloWorld
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:
If you saved that code in a file called
HelloWorld.scala
then you could compile and run it like so:Or if you are working in the REPL:
or