does kotlin have a magic fromString function for u...
# announcements
g
does kotlin have a magic fromString function for use with reflection? I've got a
value: string
and a
KPropoperty1<*, T>
, and I'm certain that the
value
is a `toString()`'d version of
T
and that
T
is a common value type (eg
String
,
Double
, or
enum class
). Is there a handy way for me to convert from my
value
to an instance of the `KProperty`'s return type? I can write the switch but I sorta feel like somebody should've handled this for me. I've got both guava and apache commons on my classpath
Copy code
fun KType.fromString(valueString: String) = when(val typeClassifier = classifier){
    Double::class -> {

    }
    String::class -> {

    }
    is KClass<*> -> {
        if(Enum::class.isSuperclassOf(typeClassifier)){
            
        }
        TODO()
    }
    else -> TODO("$valueString as $typeClassifier")
}
I could flesh that out but its a bunch of work
c
There is no strong relationship between an object and what is returned from
toString
. You could have it return whatever you want, and in many cases
toString
is intended to return a human-readable String, but not a machine-readable one.
That said, maybe #serialization is what you’re looking for?
g
yeah thats a good call, but I am thinking specificaly about java stack types, + string, + enums
all of which have bi-directional functinos built-in
(IE double.parseDouble() is a dual to double.toString()), similarly
Enum.valueOf()
and
enum.toString()
--assuming of course you have some side-channel to keep schema (IE the type
k
You could put your string in some json and use whatever lib to parse that, it'll handle all of the primitives and possibly dates. It's hacky, but what you're doing is hacky in the first place!