https://kotlinlang.org logo
Title
r

Robert

10/29/2020, 8:35 PM
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

Ryan

10/29/2020, 8:38 PM
depends
you can do this val someVarName by lazy { “some value” }
val isEmpty: Boolean get() = this.size == 0
r

Robert

10/29/2020, 8:42 PM
The second example wouldnt support setting a value for ‘isEmpty’ directly, right?
r

Ryan

10/29/2020, 8:42 PM
right
e

ephemient

10/29/2020, 8:42 PM
well no, as written there is no backing field
r

Robert

10/29/2020, 8:43 PM
Okay, then I guess the first solution is the best match. At least, I think i can set value in that case..
r

Ryan

10/29/2020, 8:44 PM
the first solution is if the value doesn’t change
r

Robert

10/29/2020, 8:47 PM
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

Ryan

10/29/2020, 8:47 PM
you can do a var
r

Robert

10/29/2020, 8:47 PM
var someVarName by lazy {
"some value"
}
Just like this?
e

ephemient

10/29/2020, 8:48 PM
no, lazy doesn't work with var
r

Ryan

10/29/2020, 8:48 PM
var k = “foot” get() { return field }
i think u can do that
but your splitting hairs
r

Robert

10/29/2020, 8:49 PM
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

ephemient

10/29/2020, 8:49 PM
there's nothing built in for that use case. you can expand the code yourself
private var _isEmpty: Boolean? = null
var isEmpty: Boolean
    get() = _isEmpty ?: throw UninitializedPropertyAccessException("property isEmpty has not been initialized")
    set(value) {
        _isEmpty = value
    }
r

Ryan

10/29/2020, 8:50 PM
look into the lazy keyword
you can expand on that
e

ephemient

10/29/2020, 8:50 PM
lazy is function in the standard library, not a keyword
lateinit is a keyword, but doesn't work on primitive types
👍 1
r

Robert

10/29/2020, 8:50 PM
@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

Ryan

10/29/2020, 8:50 PM
lateinit is trash imop
e

ephemient

10/29/2020, 8:51 PM
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
import kotlin.properties.Delegates
var someVarName: String by Delegates.notNull()
someVarName = "some value"
r

Robert

10/29/2020, 9:24 PM
Thanks, will look into that. Not sure how it works, but sure google can tell me 😉