Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a getter return a non-nullable type even though the backing field is nullable

num should be nullable when set, but what it returns should always be non-nullable (have a default value).

class Test {
    var num: Int? = null
        get() = field ?: 5 // default value if null
}

The following does not compile even though the returned value is always non-null which makes sense to me, because the type is not inferred but taken from the backing field:

val a: Int = Test().num

Type mismatch: inferred type is Int? but Int was expected

The question is how can I change the return type of that getter to be non-nullable? If I do so, the compiler says:

Getter return type must be equal to the type of the property, i.e. 'Int?'


I know that I could solve it with another property numNotNullable (without a backing field).

class Test {
    var num: Int? = null
        get() = field ?: 5 // default value if null

    val numNotNullable: Int
        get() = num ?: 5
}

val c: Int = Test().numNotNullable

But this is not what I want. Is there another way?

like image 980
Willi Mentzel Avatar asked Dec 24 '22 13:12

Willi Mentzel


1 Answers

var num: Int? = null

This is your property signature. It doesn't matter, if you internally ensure that no null value is returned. The signature says, that the value is nullable.

This implicates:

  • You are allowed to set null to this field
  • All classes using this field, must handle the fact that the property can return null

Your Solution with a second property is good.

You of course can replace the property with plain old java bean, but I wouldn't advise that, because than you have to access the prop with getNumb and setNum.

class Test {
    private var num: Int = 5

    fun setNum(num: Int?) {
        this.num = num ?: 5
    }

    fun getNum() = num
}
like image 54
guenhter Avatar answered Dec 28 '22 06:12

guenhter