How can I convert Any objects to objects of the correct types knowing only the names?


#1

Hello everyone,

I find the Kotlin Any object very very useful. However, when I get a result as an Any object “result”, I need to convert it to the correct type, for example, “CorrectTypeName”. I know we can do something like “result as CorrectTypeName”, but is there another way around to do it?

I am looking for a, for example, function like “fun convert(obj: Any, typename: String): T {…}” that will input an object of type Any and its correct type name as a string, and then output that object in its correct type. Is there any way to achieve it?

Thank you so much for your time and consideration.


#2

Not really. The problem is that you are trying to convert from information you only know at runtime to information you need to know at compile time. You could do something with predefined paths, where you for example only execute code if the obj is of type String or Foo, etc.

when(typename){
    "String" -> doSomethingWithString(obj as String)
    ....
}

#3

It is possible to cast an object to a type derived from its name at runtime.
You can get java class from string using Class.forName(...) method and then use Java Class::cast(documentation here) to perform safe cast. But since the type information is accessible only in runtime, compiler won’t be able to use it. So the type will be correct, but you cant designate it as T,. It is sometimes useful, when you are using type from some external configuration and generating objects by reflections, but should be avoided otherwise.

Another possibility is the usage of kotlin reified inline function types:

inline fun <reified T: Any> Any.cast(): T{
  return this as T
}

val a: Any
val b = a cast<B>()

But I cant’t see how it is better then simple cast.


#4

The compiler should convert this to a simple cast. I mean it is an inline reified function which by definition will be inlined :slight_smile:


#5

I mean syntax. It is obvious that in the end any static cast will be reduced to language cast operation.


#6

Maybe this syntax is better if the type of the cast can be inferred or if you prefere any.cast<B>().doSomething() over (any as B).doSomething().


#7

It’s dangerous, what you need is generics.


#8

Thank you all. Thanks to your answers, I finally know that it is impossible to do it nicely, so I have to need to struggle to find a way anymore. Thank you.