How do I create a property, if I don’t want it to ...
# getting-started
r
How do I create a property, if I don’t want it to be null, and don’t want to initiate a (default) value unless it is being called (unless manually a value has been set). Do I need field + getter + setter + private backing field? Or is there an easier way?
r
depends
you can do this val someVarName by lazy { “some value” }
val isEmpty: Boolean get() = this.size == 0
r
The second example wouldnt support setting a value for ‘isEmpty’ directly, right?
r
right
e
well no, as written there is no backing field
r
Okay, then I guess the first solution is the best match. At least, I think i can set value in that case..
r
the first solution is if the value doesn’t change
r
Ah, so it doesn’t support setting value either. What if I want to be able to override the lazy value by setting it?
someVarName = "other value"
print(someVarName) // should output "other value", not "some value"
r
you can do a var
r
var someVarName by lazy {
"some value"
}
Just like this?
e
no, lazy doesn't work with var
r
var k = “foot” get() { return field }
i think u can do that
but your splitting hairs
r
But then I need to initialize a value every time (“foot”) which gets expensive with complex objects. I would prefer to only initialize it when I use it (if not set)
e
there's nothing built in for that use case. you can expand the code yourself
Copy code
private var _isEmpty: Boolean? = null
var isEmpty: Boolean
    get() = _isEmpty ?: throw UninitializedPropertyAccessException("property isEmpty has not been initialized")
    set(value) {
        _isEmpty = value
    }
r
look into the lazy keyword
you can expand on that
e
lazy is function in the standard library, not a keyword
lateinit is a keyword, but doesn't work on primitive types
👍 1
r
@ephemient Yeah that was my original use case indeed, with a private backing field. Was wondering if I could do it simpler. But probably cant in this case
Ty both
r
lateinit is trash imop
e
well, you can abstract that same logic out to your own delegated property if you need it
come to think of it
if your type is non-nullable, then
Delegates.notNull()
may suit your purposes
Copy code
import kotlin.properties.Delegates
var someVarName: String by Delegates.notNull()
someVarName = "some value"
r
Thanks, will look into that. Not sure how it works, but sure google can tell me 😉