Kotlin vs Java
Null Safety
- Java: variables are nullable.
NullPointerExceptionis a common issue. - Kotlin: variables are non-nullable by default (to avoid
NPE); use?for nullable variables, e.g.var a: String?
Data Class and Records
Kotlin data class is similar to Java record, with some differences:
- Java
recorddoes not havecopy()method. data classvariables can bevarorval;recordvariables are allfinal.data classcan inherit from other non-data classes;recordhas no inheritance.data classcan define non-constructor mutable variables;recordcan define only static variables.
Coroutines
- Kotlin supports coroutines in an extension library
kotlinx.coroutines. (Not at the language level or in the standard library.) - Java: Project Loom is trying to add coroutines / fibers to Java but it is not finished yet.
Extensions
- Kotlin: provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.
- Java: you have to create a new class and inhrit from the parent class.
Checked Exceptions
- Kotlin: no checked exceptions, developers do not need to declare or catch exceptions.
- Java: have both checked and unchecked exceptions.
Companion Object
- Java: use
statickeyword to declare class members (used without an instance). - Kotlin: no
statickeyword but can use acompanion object.
Class Inheritance
- Java: methods can be overridden by default; a
finalclass cannot be subclassed. - Kotlin: classes cannot be inherited by default; a
openclass can.
Sealed Class
Both Kotlin and Java (since Java 17) support Sealed Class.
Before Java 17, Java has the following options for inheritance control:
- A
final classcan have no subclasses. - A package-private class can only have subclasses in the same package.
switch vs when
-
Java uses
switch:switch ( ... ) { case X: ... case Y: ... default: ... } -
Kotlin uses
when:when ( ... ) { condition -> ... condition -> ... else -> ... }
Operator Overloading
- Kotlin supports operator overloading; Java does not.