Sobes.tech
Junior

What key features distinguish Kotlin from Java?

sobes.tech AI

Answer from AI

Coroutines, extensions, null safety, data classes, more concise syntax for many constructs (e.g., lambda expressions, conditional operators, iterations).

Feature Kotlin Java
Null Safety Built-in support at the type system level. Can result in NullPointerException at runtime.
Extensions Ability to add new functions to existing types without inheritance. No direct support.
Coroutines Lightweight threads for asynchronous programming. Traditional heavy threads (or third-party libraries like Project Loom).
Data Classes Automatically generate equals(), hashCode(), toString(), copy(). Must be implemented manually (or use Lombok).
Smart Casts Compiler automatically performs type casting after type checks. Requires explicit casting.
Lambda Expressions More concise syntax. More verbose syntax.
Nested Classes Inner classes are nested by default (nested). Inner classes are inner by default (inner).
Mutable/Immutable Separation of collections into mutable and immutable. No explicit separation in the collection type system.
Operator Overloading Support for operator overloading. No support.
// Example of a data class
data class User(val name: String, val age: Int)

// Example of an extension function
fun String.addExclamation(): String = this + "!"

// Example of null safety
var nullableString: String? = null
// nullableString.length // Compilation error if not checked

// Example of a coroutine
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch { // Launches a new coroutine and continues
        delay(1000L) // Non-blocking delay of 1 second (default time unit is ms)
        println("World!")
    }
    println("Hello") // Main coroutine continues while child is running
}
// Equivalent of a data class in Java (without Lombok)
public class User {
    private final String name;
    private final int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }

    // Manual implementation of equals(), hashCode(), toString() needed
}

// NullPointerException in Java
String nullableString = null;
// int length = nullableString.length(); // Runtime Exception: NullPointerException
What key features distinguish Kotlin from Java… - sobes.tech