Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - nonnull getter for a nullable field

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?

like image 467
awfun Avatar asked Nov 21 '16 09:11

awfun


1 Answers

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
like image 51
F. George Avatar answered Sep 18 '22 00:09

F. George