Ouch, seems that I can't override abstract `String...
# getting-started
v
Ouch, seems that I can't override abstract
StringConverter<T>
with another parametric class
r
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
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
Oh, okay, so you would want to do a typecheck on
T
inside the
toString
function?
v
Exactly
r
Well you can always just check the type of the parameter that's coming in, so for example you could do it like this:
Copy code
class AnyConverter : StringConverter<Any> {
    fun toString(value: Any): String {
        when (value) {
            is String -> TODO()
            is Int -> TODO()
            else -> TODO()
        }
    }
{
👍 1
v
Cool
r
Oh and I forgot to say that still works if the class is parameterized:
Copy code
class Converter<T> : StringConverter<T> {
    fun toString(value: T): String {
        when (value) {
            is String -> TODO()
            is Int -> TODO()
            else -> TODO()
        }
    }
{
v
But for
Copy code
fun fromString(value: String?): Any {
}
it seems not so simple
r
That's true. To get it there without having something else to go on this is what I would do:
Copy code
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
I thought of passing any variable to the class constructor like:
Copy code
class MyConverter<T>(data: T): StringConverter<T> {
}
r
Yeah, see my message - I was faster 😛
v
Is it neccessary to make
clazz
val
?
r
yeah, otherwise you can't access it from within a function body. You can make it private though.
v
Thanks