Kotlin Multiplatform Mobile question... I have the...
# announcements
c
Kotlin Multiplatform Mobile question... I have the following:
Copy code
inline fun <reified T : Any> jsonToConfig(stringJson: String): T? =
    Json.decodeFromString<T?>(stringJson)
Using Kotlinx Serialization decoding from the string works fine in Kotlin. But in Swift: let projectConfig: ProjectConfig? = config.jsonToConfig<ProjectConfig>(stringJson: jsonString) I get the following error: "Cannot explicitly specialize a generic function". Any ideas how I could go about getting this to work?
a
Swift doesn't support the Kotlin call site specialization syntax e.g.
obj.foo<Type1, Type2>()
. But most importantly, there is no concept of "generic functions" in Objective-C, only generic classes. So if you inspect the function signature which Swift imports from Objective-C, you will see it isn't a generic function at all. like
Copy code
class FileNameKt {
    class func jsonToConfig(string: String): Any?
}
and I am not sure what will happen when you call it. Undefined behaviour likely. You will either need to define a non-generic version that calls the generic version, or wrapping the function into a generic class if you do need to have it available in its generic form in ObjC/Swift.
Copy code
fun jsonToMyConfig(string: String): MyConfig? = jsonToConfig<MyConfig>(string)
or
Copy code
class Converter<T: Any> {
  fun convert(string: String): T? = jsonToConfig<T>(string)
}
c
Thanks for info. I'm trying to get the generic form working but when I tried using your example I get "Cannot use T as reified type parameter. Use a class instead".
l
@Cdev What you are trying to do can only be done in Kotlin code. Wrap it so before calling from Swift.
1
c
Makes sense, thanks.