spleenjack
10/01/2024, 2:47 PMval property: Int? by delegate(…)
but this should be ok val property: Int by delegate(…)
.
data class Holder<T : Any>(val value: T)
fun <T : Any> delegate(holder: Holder<T>) =
ReadOnlyProperty<Any, T> { _, _ -> holder.value }
class Foo {
// ERROR: Type argument is not within its bounds: should be subtype of 'kotlin. Any'.
val holder = Holder<Int?>(1)
// why OK?
val property: Int? by delegate(Holder(1))
}
Youssef Shoaib [MOD]
10/01/2024, 2:56 PMval
property, the only check that kotlin does is to make sure that the property type is a supertype of the delegate's getValue
type. In other words, this works for the same reason that:
val property: Int? = Holder(1).value
works.Sam
10/01/2024, 2:56 PMval property: Int? = 1
...spleenjack
10/01/2024, 3:11 PMT : Any
appears for the generic type? In my case a holder throws a runtime exception if the value is null, so it would return only non-nullable values. If I add a double-bang operator like this { _, _ -> holder.value!! }
there is a warning “Unnecessary non-null assertion (!!) on a non-null receiver of type ‘T’.” So I expect that compiler assumes that a nullable type Int?
with such a restriction is not a valid case.Sam
10/01/2024, 3:13 PMval property: Int? by delegate<Int>(Holder<Int>(1))
You're certainly correct that delegate<Int?>(…)
would not be valid. But delegate<Int>(…)
is always going to be a valid delegate for any supertype of Int
, including Int?
ephemient
10/01/2024, 3:20 PMprivate val propertyDelegate = delegate(Holder(1))
val property: Int?
get() = propertyDelegate.getValue()
which is not an error. the IDE does warn about that ?
in similar circumstances though, so perhaps file a feature request in YouTrackspleenjack
10/01/2024, 3:22 PM