Can a field be cast to non null version of itself?

Viewed 413

I have a data class

data class MyModel(private val _data: MyData? = null)

And I want to ensure my data is only accessible when it is not null, else throw. I use the below which is good.

    fun getData(): MyData {
        return checkNotNull(_data) { "data shouldn't be null" }
    }

However, if I follow the guide as per Override getter for Kotlin data class, the below complaints I need to return MyData? instead of MyData

val data = _data
    get(): MyData {
        return checkNotNull(field) { "data shouldn't be null" }
    }

Is it true that field can't be cast to the Non-null version of it when return?

3 Answers
Related