Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class declaration in Java vs in Kotlin

Tags:

java

kotlin

I am new to Kotlin and I have the following doubt -

Using the Java to Kotlin converter (this Link), I converted the following Java code to Kotlin.

Java Class:

  public class Person { 
    private String name; 
    private int age; 

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
  }

Generated Kotlin Class:

class Person(name:String, age:Int) {
  var name:String
  var age:Int = 0
  init{
    this.name = name
    this.age = age
  }
}

But I don't understand how the Java Code and the generated Kotlin code are equivalent because the visibility modifiers of the class data members change from private(in Java) to public(in Kotlin).

I believe that if the visibility modifiers are preserved(the data members are declared private in Kotlin), getters and setters will have to be created in Kotlin too and only then should they be equivalent.

like image 976
Sumanth Sugunendran Avatar asked Apr 17 '26 14:04

Sumanth Sugunendran


1 Answers

in Kotlin, it implicitly creates getters and setters for the fields (which you had in Java as well). As these are public, the fields themselves become effectively public.

Effectively your Java code with the simplistic getters and setters was the equivalent of having public fields because of the nature of the getters and setters (no validation etc.).

Had your setters done for example null checks and thrown IllegalArgumentExceptions, the code'd have been different.

like image 142
jwenting Avatar answered Apr 20 '26 02:04

jwenting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!