```val foo : String? = null bar(foo) fun bar(val...
# announcements
l
Copy code
val 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
?
s
Well, I know of a technique that would approximate what you’re looking for, but it’s important to note that
null
has no type (sort of), and the type system can’t resolve magical intent here at runtime
what you’re looking for probably looks something more like this:
Copy code
inline fun <reified T : Any> bar(value: T?) {
  when (T::class) {
    Int::class -> println("Int?")
    String::class -> println("String?")
  }
}
bar(foo)  // String?
you can use type inference to keep the call site looking clean and use
reified
to do the dirty work
l
Thanks!
Wait this doesn't solve my problem. I am actually passing
vararg
to my function and it doesn't work in that case 😔
I am trying to achieve a helper function for JDBC which will take a number of arguments and set the parameter of the prepared statement for each argument.
Copy code
fun 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
        }
    }
}
Copy code
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
d
There is no way for the compiler to know if you want a nullable string or a nullable int if all you give it is
null
.
👆 1
n
or you could just call
setObject
and let the JDBC driver/DB sort this out for you