I am new to Kotlin and I am trying to remake a small Java project into this new language. I use mongodb in my project, and I have a class, for example:
class PlayerEntity {
constructor() {}
constructor(id: ObjectId, name: String) {
this.id = id
this.name = name
}
@org.mongodb.morphia.annotations.Id
var id: ObjectId? = null
var name: String? = null
}
I have to mark the field idas nullable ( var id: ObjectId?) due to an empty constructor. When I try to access this field from another class, I have to use a non-empty check: thePlayer.id!!. But the logic of my application is that the field is idnever null (mongo creates an instance of Player and immediately sets the id field). And I do not want to do a non-zero check everywhere.
I tried to make a nonzero getter, but it does not compile:
var id: ObjectId? = null
get(): ObjectId = id!!
I can also make some stub for id and use it in the constructor, but it looks like a dirty hack:
val DUMMY_ID = new ObjectId("000000000000000000000000");
, ?