In Java I have these two classes :
public class Base {
protected Long id;
// getter setter
}
public User extends Base {
private String name;
private Integer age;
public User(Long id) { this.id = id; }
// getter setter
}
I created these two classes in Kotlin :
open class Base(var id: Long? = null)
class User(
var id: Long? = null,
var name: String? = null,
var age: Int? = null
) : Base()
Now in Java I want to call the User() constructor with only the 'id' parameter :
new User(5);
This seems wrong to me, because by doing this I re-declared the "id" field in the User class.
How can I set the id field of the base class in Kotlin (like I did in Java with "this.id = id;" ?
First, your Kotlin code would not compile, because you would get the following error: Error:'id' hides member of supertype 'Base' and needs 'override' modifier
.
Basically, the compiler would also complain that you redeclared id
from Base
, in User
.
If you want to redeclare it, you need to first make id
open in Base
, and then in User
, you need to use the override keyword, when redeclarding id
. (also see this)
Furthermore, for the Kotlin compiler to generate overloads of the User
constructor, you need to annotate your primary constructor with @JvmOverloads. Without @JvmOverloads, you wouldn't be able to use the User(id)
constructor (just id
as param) in Java, and would have to specify all 3 parameters.
So your code would become:
open class Base(open var id: Long? = null)
class User @JvmOverloads constructor(override var id: Long? = null,
var name: String? = null,
var age: Int? = null
) : Base(id)
Now, if you don't want to redeclare id
in User, you can simply not use var
in front of it, and instead pass it directly to Base
, when calling its constructor. So basically this:
open class Base(var id: Long? = null)
class User @JvmOverloads constructor(id: Long? = null,
var name: String? = null,
var age: Int? = null
) : Base(id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With