https://kotlinlang.org logo
Title
v

ValV

09/26/2018, 4:18 PM
Ouch, seems that I can't override abstract
StringConverter<T>
with another parametric class
r

robin

09/26/2018, 4:25 PM
A class defined as
BooleanStringConverter : StringConverter<Boolean>
should definitely be assignable to
StringConverter<Boolean>
. Or am I misunderstanding what you're trying to do?
v

ValV

09/26/2018, 4:29 PM
There are two functions:
fromString(String?): T
and
toString(T): String
which I would like to override for a couple of cases
And do not want to create a separate class for each type
r

robin

09/26/2018, 4:31 PM
Oh, okay, so you would want to do a typecheck on
T
inside the
toString
function?
v

ValV

09/26/2018, 4:32 PM
Exactly
r

robin

09/26/2018, 4:34 PM
Well you can always just check the type of the parameter that's coming in, so for example you could do it like this:
class AnyConverter : StringConverter<Any> {
    fun toString(value: Any): String {
        when (value) {
            is String -> TODO()
            is Int -> TODO()
            else -> TODO()
        }
    }
{
👍 1
v

ValV

09/26/2018, 4:36 PM
Cool
r

robin

09/26/2018, 4:38 PM
Oh and I forgot to say that still works if the class is parameterized:
class Converter<T> : StringConverter<T> {
    fun toString(value: T): String {
        when (value) {
            is String -> TODO()
            is Int -> TODO()
            else -> TODO()
        }
    }
{
v

ValV

09/26/2018, 4:40 PM
But for
fun fromString(value: String?): Any {
}
it seems not so simple
r

robin

09/26/2018, 4:43 PM
That's true. To get it there without having something else to go on this is what I would do:
class Converter<T>(val clazz: KClass<T>) : StringConverter<T> {
    fun fromString(value: String): T {
        when (clazz) {
            String::class -> TODO()
            Int::class -> TODO()
            else -> TODO()
        }
    }
    companion object {
        operator inline fun <reified T> invoke() = Converter(T::class)
    }
}
v

ValV

09/26/2018, 4:44 PM
I thought of passing any variable to the class constructor like:
class MyConverter<T>(data: T): StringConverter<T> {
}
r

robin

09/26/2018, 4:44 PM
Yeah, see my message - I was faster 😛
v

ValV

09/26/2018, 4:45 PM
Is it neccessary to make
clazz
val
?
r

robin

09/26/2018, 4:45 PM
yeah, otherwise you can't access it from within a function body. You can make it private though.
v

ValV

09/26/2018, 4:46 PM
Thanks