can i find out inside a generics function if the t...
# announcements
r
can i find out inside a generics function if the type is nullable or not.
k
Normally you can't find out anything from a generic parameter, but if it's
reified
you can do
null is T
.
😲 1
🤯 1
t
Not sure if it is possible, but you can enforce non-null generic parameter :
Copy code
fun <T : Any> withNonNull(foo: T)
r
☹️ require something like if nullable do this else that
t
Maybe you could share some code, so that we can suggest you an alternative approach ?
r
was trying to create a utility for property delegation from map
Copy code
private infix fun <Key, T, Value, Return : Value> <http://Key.at|Key.at>(map: MutableMap<Key, Value>): ReadWriteProperty<T, Return?> {
    return object : ReadWriteProperty<T, Return?> {
        override fun setValue(thisRef: T, property: KProperty<*>, value: Return?) {
            if (value != null) { // should be only done if Value is non nullable type
                map[this@at] = value
            }
        }

        override fun getValue(thisRef: T, property: KProperty<*>) = map[this@at] as Return?
    }
}
usage is something like
Copy code
var value: String? by PROPERTY_KEY at mutableMap
k
Then just do what I said?
r
even if i do what you said. compiler won’t let me put a nullable value in map as it still doesn’t understand if it is nullable.
was hoping language has this funcnality
k
What is "should be only done if Value is non null " supped to mean? Do you mean "Value is a nullable type" or "value is not null"?
r
if check should only be done if
Value
is non nullable type. (updated on file above)
k
Ah I see what you mean. Looks like this is indeed not supported, even in new type inference it doesn't work.
☹️ 1
r
assuming there is a property
a
using this delegate.
a = null
should update value in map if map has nullable type, but if map is non nullable this should just ignore it.
found workaround for my use-case. 🙂 It got me thinking this problem should happen even for a normal map with non nullable value. To remove a key I don’t need to do
map[key] = null
, but instead i can do
map.remove(key)