0

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

2 Answers2

1

How about

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

?

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
1

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.

Pawel
  • 15,548
  • 3
  • 36
  • 36
  • Yeah, and also would cause unexpected runtime crashes if, for example, you had `private val myValue: Int?` and later `myValue = sharedPreferences["key"]` and then someone changed `myValue` to `String?`. Nothing would fail to compile but at runtime you're going to be trying to cast an Int to a String. Better to be type-safe! – Kevin Coppock Oct 17 '18 at 23:25