Hi!
I’m just starting out with kotlin and i was trying to build a simple data class with custom getters/setters. What i want would look like this in Java:
public class JavaPerson {
private final String name;
private int age;
public JavaPerson(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
// default name getter, no setter
// default age getter
public void setAge(final int age) {
System.out.println("Setting age to " + age);
this.age = age;
}
}
However i struggle to get the same thing working in kotlin:
public class Person(val name: String, var age: Int) {
override fun setAge(age: Int) {
println("Setting age to " + age);
this.age = age
}
// doesn't compile: overrides nothing
public fun setAge(age: Int) {
println("Setting age to " + age);
this.age = age
}
// fails at compile and/or runtime: java.lang.ClassFormatError: Duplicate method name&signature in class file de/itso/kotlintest/Person
}
I’ve also tried to do it like this:
public class Person private constructor (val name: String) {
private var age: Int
public constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
But this fails, as i have to initialize age when i declare it, although i assign it in the only public constructor. I would consider this a workaround, even if it compiled.
Can anybody help me here?