https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

02/21/2023, 1:33 PM
Copy code
interface Foo<T> {
    fun getValue(): T
    fun removeValue()
    fun setValue(value: T) // is there a way to only allow non-null values?
}

interface NonNullFoo<T: Any>: Foo<T>
interface NullableFoo<T: Any>: Foo<T?>
s

Sam

02/21/2023, 1:33 PM
Definitely-non-nullable types! K
Copy code
fun setValue(value: T & Any)
🙏 1
m

Mark

02/21/2023, 1:44 PM
That’s really good to know thanks, but how can I then define a delegated property?
Copy code
val <T> Foo<T>.valueProperty: ReadWriteProperty<Any, T>
    get() = object : ReadWriteProperty<Any, T> {
        override fun getValue(thisRef: Any, property: KProperty<*>): T {
            return getValue()
        }

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            setValue(value) // compile error: require T & Any
        }
    }
Oh it looks like you can just do a runtime check for
value == null
Copy code
val <T> Foo<T>.valueProperty: ReadWriteProperty<Any, T>
    get() = object : ReadWriteProperty<Any, T> {
        override fun getValue(thisRef: Any, property: KProperty<*>): T {
            return getValue()
        }

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            if (value == null) {
                removeValue()
            } else {
                setValue(value)
            }
        }
    }
🐕 1
6 Views