Eduardo Oviedo Blanco
Eduardo Oviedo Blanco

Reputation: 455

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

Upvotes: 0

Views: 370

Answers (2)

Pawel
Pawel

Reputation: 17288

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.

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81578

How about

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

?

Upvotes: 1

Related Questions