Kotlin - nonnull getter for field with zero value

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() {} //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 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");

, ?

+4
1

private var _ + public val .

class Example<out T> {
  private var _id: T? = null
  val id: T
    get() = _id!!
}

:

@org.mongodb.morphia.annotations.Id
private var _id: ObjectId? = null
val id: ObjectId
  get() = _id!!

lateinit :

@org.mongodb.morphia.annotations.Id
lateinit var id: ObjectId
+3

Source: https://habr.com/ru/post/1661433/


All Articles