JavaRush /Java Blog /Random EN /KotlinRush: does it make sense to continue writing in Jav...
NikEy
Level 41
Новосибирск

KotlinRush: does it make sense to continue writing in Java?

Published in the Random EN group
Hello, JavaRush student, before you are completely absorbed by Java, I would like to expand your horizons and draw attention to the increasingly popular Kotlin language !
KotlinRush: does it make sense to continue writing in Java?  - 1
Kotlin is a fairly young language developed by JetBrains . Yes, yes, the very 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. What about libraries: Kotlin and Java classes can coexist in one package! Kotlin was so popular with the programming community that Google recognized it as the official development language for Android, and recently Kotlin has begun to gain popularity in enterprise projects. In this article, I would like to give several comparative examples of code written in Kotlin and Java, and draw some conclusions. Go! Let's start, as usual, 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 fun keyword ;
  • To print a line, just one word is enough - println() !
Creating an Instance
// Java (до 10)
final Application application = new Application();
// Kotlin
val application = Application()
Kotlin differences:
  • there is no need to declare the type of a variable if it is clear from the instance;
  • instead of the variable type - val (immutable) or var (changeable);
  • 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 a 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 method body consists of 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, just use the "$" symbol at the beginning of the variable. This notation significantly improves the cleanliness and readability of the code. Instance Comparison
// Java
object1.equals(object2)
// Kotlin
object1 == object2
In Kotlin, the comparison " ==" for object types is translated to equals! And to compare links, " ===" 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 create multi-level exceptions 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” in 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 there's Null on the left, take what's on the right. In the case of our example, when the value variable 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 it is called 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 simply use a variable on the left , a sequence on the right , and the keyword “ in ” in between, 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 “ singler ” 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; when used, you don’t even need to call the constructor or any other 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 must be required, and in Java we are used to creating a set of methods or constructors for every possible combination of parameters. Default parameters have been introduced into Kotlin, which allows you to declare 1 method and pass the required set of parameters to it depending on 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 stream in Java 8 has become an integral functionality when working with collections. In Kotlin, streams have been made even more convenient and functional: each collection already has a set of convenient, frequently used methods for working with data. Also, notice the lambda expression inside the first method: if a function literal has exactly one parameter, its declaration can be removed (along with the ->), and referred to as  it . It's time to wrap up... I demonstrated only a small, basic part of the functionality, but I'm sure you already want to try Kotlin! From my experience I can draw the following conclusions:
  • It is very easy for a Java developer to master the Kotlin syntax and start writing code;
  • Kotlin is fully compatible with Java, and you can already try it in your existing projects, for example, in tests;
  • Kotlin code is cleaner and more readable, you don’t 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, because from an infrastructure point of view it’s the same as Java, but in terms of use it’s better and more convenient!
If you liked the article and are generally relevant on a resource about Java, I can continue writing 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