Hey, generic wizards. I have another one for you. ...
# announcements
a
Hey, generic wizards. I have another one for you. Among these two, which one is the recommended one? and most importantly, why?
Copy code
//case A
inline reified fun <T:Any?> T.doThing(name: String = T::class.simpleName ?: "") {}
or
Copy code
//case B
inline reified fun <T:Any> T?.doThing(name: String = T::class.simpleName ?: "") {}
s
Don't know.... depends on the implementation of the actual function. It depends whether you want the
this
extension receiver to be nullable or not (and
<T : Any?>
can be abbreviated to just
<T>
).
z
Assuming you moved
reified
to the correct place, I don’t think 1 would compile -
KClass
can only refer to non-nullable class types
m
Example for a use case:
CharSequence?.isNullOrEmpty()
Copy code
val str: String? = null
if(str.isNullOrEmpty()) { ... }

// vs isEmpty

if(str?.isEmpty() == true) { ... }
// equals required for nullable booleans.
n
why not
Copy code
inline fun <reified T:Any> T.doThing(name: String = T::class.simpleName ?: "") {}
actually. TBH, your function is a bit weird because it's not actually using the instance at all.
and you're already going the inline/reified route. So why not:
Copy code
//case D
inline fun <reified T:Any> doThing(name: String = T::class.simpleName ?: "") {
    println(name)
}
so you don't need to have an instance to call it at all