Search code examples
kotlinextension-function

Kotlin extension function to an unknown type


Is it possible to use an extension function with a function that returns an unspecified value type?

defaultPreferences(this)["some string"]?.let { ...

I have to do this to avoid error, but I really want it to be in a single line.

val value: String? =  defaultPreferences(this)["some string"]
value?.let { ...

And the error I get in the first example is

"Type inference failed: Not enough information to infer parameter T in inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = ...): T?
Please specify it explicitly."

Any ideas?

Edit: More information

Here is the declaration of the get function.

inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? {

Solution

  • How about

    defaultPreferences(this).get<String?>("some string")?.let {
    

    ?