From Java to Kotlin: How Would You Rewrite This Class?
Source: Dev.to
Understanding What This Class Does
Before jumping to Kotlin, let’s break down what this Java class actually contains:
- Two private fields (
codigoandnome) that are set via the constructor - Two private fields with default values (
numero = 0andtexto = "EscolaX")
A constructor receives codigo and nome as parameters and assigns them using this.
Step 1: The Class Declaration
Java
public class AlunoJava { ... }
Kotlin
Classes are public by default, so you don’t need the public keyword:
class AlunoKotlin { ... }
✅ No public needed — less boilerplate from the start.
Step 2: The Constructor
Java constructor
public AlunoJava(String codigo, String nome) {
this.codigo = codigo;
this.nome = nome;
}
Kotlin primary constructor (declared in the class header). Adding val or var creates the fields automatically:
class AlunoKotlin(private val nome: String, private val codigo: String) {
// nome and codigo are already declared AND assigned here!
}
✅ The constructor declaration, field declaration, and assignment all happen in one line.
Step 3: val vs var
val→ immutable (likefinalin Java) — value can’t be reassigned after initialization.var→ mutable — value can be changed later.
Since the original Java class doesn’t reassign codigo or nome after construction, val is the more faithful and idiomatic translation.
Step 4: Fields With Default Values
Java fields
private int numero = 0;
private String texto = "EscolaX";
Kotlin equivalents (type inference applies):
private var numero = 0 // inferred as Int
private var texto = "EscolaX" // inferred as String
✅ We use var here because these fields may be changed later (they weren’t final in Java).
The Final Result
Putting it all together:
class AlunoKotlin(private val nome: String, private val codigo: String) {
private var numero = 0
private var texto = "EscolaX"
}
Side‑by‑side comparison
Java (17 lines)
public class AlunoJava {
private String codigo;
private String nome;
private int numero = 0;
private String texto = "EscolaX";
public AlunoJava(String codigo, String nome) {
this.codigo = codigo;
this.nome = nome;
}
}
Kotlin (3 lines)
class AlunoKotlin(private val nome: String, private val codigo: String) {
private var numero = 0
private var texto = "EscolaX"
}
Same behavior. A fraction of the code. 🎯
Key Takeaways
| Java concept | Kotlin equivalent |
|---|---|
public class | class (public by default) |
| Separate constructor block | Primary constructor in class header |
this.x = x assignment | val/var in constructor parameters |
private String x | private val x: String |
Type before name (String x) | Type after name (x: String) |
final field | val |
| Mutable field | var |
Conclusion
Kotlin was designed to eliminate Java boilerplate without sacrificing clarity. Once you get used to the primary constructor syntax and the val/var distinction, most simple Java classes translate to Kotlin naturally — and end up much shorter.