https://kotlinlang.org logo
#codereview
Title
# codereview
t

tipsy

09/13/2018, 11:25 PM
thanks @Pavlo Liapota, i actually ended up doing this:
Copy code
private val converters = mapOf<Class<*>, (String) -> Any>(
        Int::class.java to { s -> s.toInt() },
        Integer::class.java to { s -> s.toInt() },
        Double::class.java to { s -> s.toDouble() },
        Long::class.java to { s -> s.toLong() },
        Date::class.java to { s -> Date(s) }
)

fun <T> getAs(clazz: Class<T>, converter: ((String) -> T)? = null): T {
    val c = converter ?: converters[clazz] ?: throw IllegalArgumentException("Can't auto-cast to $clazz. Add a converter as a second argument.")
    return try {
        c.invoke(value)
    } catch (e: Exception) {
        ...
    } as T
}
g

gildor

09/14/2018, 3:11 AM
also can be reified
t

tipsy

09/14/2018, 7:31 AM
i have a reified version calling this one
need to support java too
👍 1
3 Views