How do you convert Java code to Kotlin?

← Kotlin answers

In Android Studio or IntelliJ, open the Java file and choose Code > Convert Java File to Kotlin File, or paste Java code into a Kotlin file and accept the conversion prompt.

// Java
public class Greeter {
    private final String name;
    public Greeter(String name) { this.name = name; }
    public String greet() { return "Hello, " + name; }
}
// Kotlin after conversion, tidied up
class Greeter(private val name: String) {
    fun greet() = "Hello, $name"
}
  • Review nullability: the converter marks types as nullable when it cannot prove otherwise. Java annotations such as @NonNull and @Nullable improve the result.
  • Convert one file at a time and compile after each, so problems are easy to place.
  • Afterwards, replace getters and setters with properties, loops with collection functions, and null checks with ?. and ?:.
  • Keep the converted file in version control history by committing the rename separately.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required