简体   繁体   中英

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? {

How about

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

?

If your inline function is what I think it is ( when on T::class and different typed gets like getString , getInt etc. with unsafe cast of the result) You should refrain from using it.

While slightly shorter to type it generates a lot of garbage bytecode, and puts unnecessary strain during runtime ( when cases are evaluated when program runs - but You already know their outcome before compiling).

For some bytecode samples You can see my answer to related question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM