JavaRush /Java Blog /Random EN /KotlinRush: is there any point in continuing to write in ...
NikEy
Level 41
Новосибирск

KotlinRush: is there any point in continuing to write in Java?

Published in the Random EN group
Hi, CodeGym student, before Java completely swallowed you up, I would like to expand your horizons and pay attention to the Kotlin language that is gaining popularity !
KotlinRush: is there any point in continuing to write in Java?  - 1
Kotlin is a fairly young language developed by JetBrains . Yes, yes, the same company that developed our favorite IDE: IntelliJ IDEA. Kotlin is a JVM language and is fully compatible with Java , that is, from Kotlin code, you can easily access familiar Java libraries. But what about libraries: Kotlin and Java classes can coexist in one package! Kotlin has been so embraced by the programming community that Google has recognized it as the official Android development language, and recently Kotlin has begun to gain popularity in enterprise projects as well. In this article, I would like to give some comparative examples of code written in Kotlin and Java, and draw some conclusions. Go! Let's start traditionally with "Hello World"
// Java
public class Application {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
// Kotlin
class Application
fun main(vararg args: String) {
    println("Hello World!")
}
Looking at the Kotlin example, we can immediately note the following:
  • no need to write a semicolon at the end of the line;
  • all methods are described by the keyword fun ;
  • just one word is enough to print a string - println() !
Instance creation
// Java (до 10)
final Application application = new Application();
// Kotlin
val application = Application()
Kotlin differences:
  • it is not required to declare the type of a variable if it is understood by the instance;
  • instead of a variable type - val (immutable) or var (mutable);
  • you don't need to write the new keyword to create an instance !
Description of methods
// Java
public int sum(int a, int b) {
    return (a + b);
}
// Kotlin
fun sum(a: Int, b: Int): Int {
return (a + b)
}
Kotlin differences:
  • if something needs to be returned from the method, " : Int " is added to the signature, where Int is the return type;
  • description of the method parameters: first the variable name, then the type;
  • since the body of the method is only one line, you can omit the return :
    fun sum(a: Int, b: Int): Int = (a+b)
Formatted string output
// Java
public int sum(int a, int b) {
    int result = (a + b);
    System.out.printf("Сумма %d и %d равна %d\n", a, b, result);
    return result;
}
// Kotlin
fun sum(a: Int, b: Int): Int {
    val result = (a + b)
    println("Сумма $a и $b равна $result")
    return result
}
Kotlin supports string interpolation, it is enough to use the "$" symbol at the beginning of the variable. Such a record significantly increases the cleanliness and readability of the code. Instance Comparison
// Java
object1.equals(object2)
// Kotlin
object1 == object2
In Kotlin, comparison " ==" for object types is translated to equals! And for comparison of references " ===" is used. Exceptions
// Java
public List<String> getFileContent(String file) throws IOException {
    Path path = Paths.get(file);
    return Files.readAllLines(path);
}
// Kotlin
fun getFileContent(file: String): List<String> {
    val path = Paths.get(file)
    return Files.readAllLines(path)
}
There are no checked exceptions in Kotlin , now you don’t need to endlessly throw an exception through the entire application or fence multilevel try-catch. Null Safety
// Java
public class Data {
    String value;

    String render() {
        if (value == null) {
            return "Value: undefined";
        } else {
            return "Value:" + value.toUpperCase();
        }
    }
}
// Kotlin
class Data {
    var value: String? = null
    fun render(): String =
            "Value: ${value?.toUpperCase() ?: "undefined"}"
}
Kotlin took care of the NPE problem and introduced a number of requirements:
  • all class fields and variables must be initialized;
  • you can write "null" into a field or variable, but then you must explicitly say that your variable is Nullable (write the sign "?");
  • The elvis operator "?:" works like this: if the left is Null, take what's on the right. In the case of our example, when the variable value is not initialized, the value " undefined " will be taken.
Class fields and access to them
// Java
public class Data {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}
class App {
    void execute() {
           Data data = new Data()
           data.setValue("Foo")
     }
}
// Kotlin
class Data {
    var value: String = ""
}
class App {
    fun execute() {
          val data = Data()
          data.value = "Foo" // Под капотом выполнится data.set("Foo")
     }
}
In Kotlin, it’s enough to simply describe a field and that’s it: it already has implicit getters and setters (hello lombok ), which can be overridden at any time if desired. At the same time, we read and modify the value of the field simply by accessing it directly, and under the hood get()|set(), . Cycles
// Java
void example() {
    for(int i = 1; i <= 10; i++) {
        System.out.println(i);
    }

    for(String line : "a,b,c".split(",")) {
        System.out.println(line);
    }
}
// Kotlin
fun example() {
    for(i in 1..10) {
        println(i)
    }

    for(line in "a,b,c".split(",")) {
        println(line)
    }
}
Kotlin has provided a convenient and uniform syntax for traversing sequences: you just use a variable on the left , a sequence on the right , and the keyword " in " between them, the type is determined automatically by the content. Singleton
// Java
public class Singleton {
    private static Singleton ourInstance = new Singleton();

    public static Singleton getInstance() {
        return ourInstance;
    }

    private Singleton() {
    }
}
class App {
    void execute() {
         Singleton singleton = Singleton.getInstance()
    }
}
// Kotlin
object Singleton {}

class App {
    fun execute() {
          val singleton = Singleton
    }
}
The familiar " loner " pattern is used quite often in practice, so Kotlin decided to create a separate keyword " object ", which is written instead of " class " and means that the class is a singleton, you don’t even need to call the constructor or any other when using methods! Named Method Parameters and Default Values
// Java
void setStatus(String code) {
    setStatus(code, "");
}

void setStatus(String code, String desc) {
    this.code = code;
    this.desc = desc;
}
// Kotlin
fun setStatus(code: String, desc: String = "") {
    this.code = code;
    this.desc = desc;
}

fun execute() {
    setStatus("200")
    setStatus(code = "200", desc = "Ok")
}
It happens that not all parameters in a method or constructor need to be required, and in Java we are used to creating a set of methods or constructors for every possible combination of parameters. Default parameters were introduced in Kotlin, which allows you to declare 1 method and pass the necessary set of parameters to it according to the situation. Streams
// Java
String getFirst(List<String> strings, String alpha) {
    return strings.stream()
            .filter(x -> x.startsWith(alpha))
            .findFirst()
            .orElse("");
}
// Kotlin
fun getFirst(strings: List<String>, alpha: String): String {
    return strings.first { it.startsWith(alpha) }
}
The introduction of streams in Java 8 has become an essential feature when working with collections. In Kotlin, streams have been made even more convenient and functional: each collection already has a set of convenient, commonly used methods for working with data. Also, note the lambda expression inside the first method: if a function literal has exactly one parameter, its declaration can be removed (along with the ->), and it can be referred to as  it . It's time to wrap it up... I've only shown a small, basic piece of functionality, but I'm sure you're already tempted to give Kotlin a try! From my experience, I can draw the following conclusions:
  • It is very easy for a Java developer to learn the Kotlin syntax and start writing code;
  • Kotlin has full compatibility with Java, and you can already try it in your existing projects, for example, in tests;
  • Kotlin code is cleaner and more readable, no need to write a bunch of boilerplate ;
  • IDEA has an automatic Java to Kotlin converter, you can take ready-made Java code and automatically convert it to Kotlin;
  • a new project needs to be written in Kotlin, since from an infrastructure point of view it is the same Java, but in terms of use it is better and more convenient!
If I liked the article and is generally appropriate for a resource about Java, I can continue to write about the experience of using Kotlin in a real enterprise project. Useful links:
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION