I'm new with Kotlin and I try to rework a small Java project to this new language. I use mongodb in my project and I have a class, for example:
class PlayerEntity {
constructor() {} //for mongodb to create an instance
constructor(id: ObjectId, name: String) { //used in code
this.id = id
this.name = name
}
@org.mongodb.morphia.annotations.Id
var id: ObjectId? = null
var name: String? = null
}
I have to mark id
field as nullable (var id: ObjectId?
) because of empty constructor. When I try to access this field from another class I have to use non-null check: thePlayer.id!!
. But the logic of my application is that id
field is never null (mongo creates an instance of Player and immediately sets id field). And I don't want to make a non-null check everywhere.
I tried to make a non-null 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 constructor, but this looks like a dirty hack:
val DUMMY_ID = new ObjectId("000000000000000000000000");
So is there a workaround to solve the issue?
I personally use a private var prefixed by _
+ public val in similiar situations.
class Example<out T> {
private var _id: T? = null
val id: T
get() = _id!!
}
For your situation, it would look like this:
@org.mongodb.morphia.annotations.Id
private var _id: ObjectId? = null
val id: ObjectId
get() = _id!!
Alternatively, declare your variable as lateinit
like this (but note that this exposes the setter publicly):
@org.mongodb.morphia.annotations.Id
lateinit var id: ObjectId
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