Lawik
02/01/2020, 8:27 PMval foo : String? = null
bar(foo)
fun bar(value: Any?){
when(value){
is Int? -> println("Int?") // always prints Int? when value == null
is String? -> println("String?")
}
}
Is there any way to get the actual type of value
?Shawn
02/01/2020, 8:38 PMnull
has no type (sort of), and the type system can’t resolve magical intent here at runtimeShawn
02/01/2020, 8:39 PMinline fun <reified T : Any> bar(value: T?) {
when (T::class) {
Int::class -> println("Int?")
String::class -> println("String?")
}
}
bar(foo) // String?
Shawn
02/01/2020, 8:39 PMreified
to do the dirty workLawik
02/01/2020, 8:52 PMLawik
02/01/2020, 9:13 PMvararg
to my function and it doesn't work in that case 😔Lawik
02/01/2020, 9:22 PMfun PreparedStatement.setParams(vararg params: Any?) {
params.forEachIndexed { index, param ->
val paramIndex = index + 1
when (param) {
is String -> this[paramIndex] = param
is String? -> this[paramIndex] = param
is Int -> this[paramIndex] = param
is Int? -> this[paramIndex] = param
is Short -> this[paramIndex] = param
is Short? -> this[paramIndex] = param
is Byte -> this[paramIndex] = param
is Byte? -> this[paramIndex] = param
is Long -> this[paramIndex] = param
is Long? -> this[paramIndex] = param
is Boolean -> this[paramIndex] = param
}
}
}
operator fun PreparedStatement.set(index: Int, value: String?) {
if (value != null) {
this.setString(index, value)
} else {
this.setNull(index, Types.VARCHAR)
}
}
// ... other PreparedStatement.set(..) functions
diesieben07
02/01/2020, 9:27 PMnull
.nkiesel
02/03/2020, 9:29 PMsetObject
and let the JDBC driver/DB sort this out for you