Can a field be migrated to a non-zero version?
I have a data class
data class MyModel(private val _data: MyData? = null)
And I want my data to be available only if it is not null, otherwise thrown. I use below which is good.
fun getData(): MyData {
return checkNotNull(_data) { "data shouldn't be null" }
}
However, if I follow the guide to override getter for Kotlin data class , below complaint I need to return MyData?
insteadMyData
val data = _data
get(): MyData {
return checkNotNull(field) { "data shouldn't be null" }
}
Is it true that field
it cannot be cast to a non-null version of it on return?
source to share
If your goal is to declare a getter for a property Any?
that returns Any
, this is not possible. You will receive the following error:
Getter return type must be equal to property type
So trying to do something like
val test : String?
get() : String = "hi"
Does not work.
However, you can hide the nullable property and expose a non-nullable property that refers to the nullable value using casting:
private val test : String? = "hi"
val testNotNull : String = test as String
If it test
references null
, an exception will be thrown.
For example:
fun main(args: Array<String>) = print(Demo().testNotNull)
class Demo(private var test: String? = "hi") {
val testNotNull : String
. get() = test as String
}
You can check this snippet at try.kotlin.org
It's not safe, though. You must rethink your design. If you don't interact with Java, you shouldn't punish yourself with null types.
source to share
I don't think you can. What you did with fun getData()
is a valid approach IMO. Or you can just not use the data class and create a normal class, obviously.
I think it might work with something like this:
typealias notNullType = MyData
data class Test(private val _value: MyData? = null) {
val v: notNullType = _value as notNullType
get() { return field }
}
This will allow you to completely:
fun play() {
val t = Test(null)
print(t.v) //see what I did? :-)
}
WHAT SAID ... I don't think "hiding" an option is ?
necessary - it's a good idea.
source to share