This article provides basic comparison of JVM languages Groovy vs. Scala vs. Kotlin with Java. For advanced feature comparison refer to Features Comparison of JVM Languages with code examples
Hello World code, compile & execute
Java:
1 2 3 4 5 |
public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello, World!"); } } |
1 2 3 |
>javac HelloWorld.java >java HelloWorld Hello, World! |
With Java 11, javac can be avoided for single file executions. Example
Groovy:
1 |
println 'Hello, World!' |
1 2 |
>groovy HelloWorld.groovy Hello, World! |
As groovy is mainly script-like language, it is run directly. But it can be compiled and executed as well.
1 2 3 |
>groovyc HelloWorld.groovy >groovy HelloWorld Hello, World! |
Scala:
1 2 3 4 5 |
object HelloWorld { def main(args: Array[String]): Unit = { println("Hello, World!") } } |
1 2 3 |
>scalac HelloWorld.scala >scala HelloWorld Hello, World! |
Kotlin:
1 2 3 |
fun main(args: Array<String>) { println("Hello, World!") } |
Notice that generated class name ‘HelloWorldKt’ is derived from file name HelloWorld.kt
1 2 3 |
>kotlinc HelloWorld.kt >kotlin HelloWorldKt Hello, World! |
Instance variable, constructor & method
Java
1 2 3 4 5 6 7 8 9 10 11 |
class MyTestClass{ String name; public MyTestClass(String name){ this.name = name; } public String myMethod(String a, int b){ String result = name + a + b; return result; } } |
Groovy
Groovy syntax is same when it comes to class, method, constructor & methods. Main intentions are to use groovy as script & not as plain old OOPS.
1 2 3 4 5 6 7 8 9 10 11 |
class MyTestClass{ String name; public MyTestClass(String name){ this.name = name; } public String myMethod(String a, int b){ String result = name + a + b; return result; } } |
Scala
Constructor is included in class definition unlike Java. Method syntax is also different i.e. <access-modifier> def <func-name> (<arg-name>:<arg-type>,...) : <return-type> = { }
1 2 3 4 5 6 |
class MyTestClass(name: String){ def myMethod(a: String, b: Int): String = { var result = name + a + b; return result; } } |
Kotlin
Many similarities with Scala here. Constructor is included in class definition. Method syntax is also somewhat similar to Scala i.e. <access-modifier> fun <func-name> (<arg-name>:<arg-type>,...) : <return-type> { }
1 2 3 4 5 6 |
class MyTestClass(val name: String){ fun myMethod(a: String, b: Int): String { var result = name + a + b; return result; } } |
Further read
Java vs. Groovy, Scala, Kotlin – Language Features Comparison of JVM Languages with code examples