Converting Java code to Kotlin involves several straightforward transformations. Below is a cheat sheet that highlights the differences and provides examples for common Java-to-Kotlin conversions:
Variable Declaration
Java:
String name = "John";
Kotlin:
val name = "John"
Nullability
Java:
String nullableValue = null;
Kotlin:
val nullableValue: String? = null
Class Declaration
Java:
public class MyClass {
// Code
}
Kotlin:
class MyClass {
// Code
}
Constructor Declaration
Java:
public class Person {
public Person(String name, int age) {
// Code
}
}
Kotlin:
class Person(val name: String, val age: Int) {
// Code
}
Getter and Setter (Properties)
Java:
public class Circle {
private double radius;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
Kotlin:
class Circle {
var radius: Double = 0.0
}
Default Argument Values
Java:
public void printMessage(String message, boolean uppercase) {
// Code
}
Kotlin:
fun printMessage(message: String, uppercase: Boolean = false) {
// Code
}
Singleton Object
Java:
public class Singleton {
private static Singleton instance;
private Singleton() {
// Private constructor
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Kotlin:
object Singleton {
// Code
}
Collections
Java:
List<String> names = new ArrayList<>();
Kotlin:
val names = mutableListOf<String>()
Lambda Expressions
Java:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Code
}
});
Kotlin:
button.setOnClickListener {
// Code
}
Coroutines
Java:
// No native support for coroutines
Kotlin:
// Using coroutines
suspend fun fetchData() {
// Code
}
This cheat sheet covers some common conversions, but it’s essential to consider the specific context and features of the original Java code. Manual adjustments may be required in certain cases. Additionally, the IntelliJ IDEA IDE provides a handy “Convert Java File to Kotlin File” feature to automate this process for individual files.