Home > Mobile >  Generic extension function Kotlin
Generic extension function Kotlin

Time:09-10

Since getParcelable is deprecated for Android Tiramisu and later i want to make an extension function to get the parcelables from my Intent through my Bundle

So i have

            val server = if (Build.VERSION.SDK_INT >= 33) {
                it.getParcelable("server", Server::class.java)
            } else {
                it.getParcelable("server")
            }

And i want to create an extension for every model like this

fun <T> T.getParcelable(bundle: Bundle, key: String): T? = 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        bundle.getParcelable(key, this!!::class.java)
    else
        bundle.getParcelable(key)

However, when i try to use it i get an unresolved reference error enter image description here

How can i fix that?

CodePudding user response:

Extension functions are actually static methods on initialised variables & not exactly on classes. That's why it isn't working.

What you can do is:

  1. You can either make your Server an object.
  2. Add a blank companion object { } to your Server class & use the below extension function.
fun <T> T.getParcelable(bundle: Bundle, key: String): T? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        bundle.getParcelable(key, this!!::class.java)
    } else bundle.getParcelable(key)
}

Example usage:

intent?.extras?.let { bundle ->
    val server = Server.getParcelable(bundle, "server")
}

CodePudding user response:

Something like this?

inline fun <reified T : Any> KClass<T>.getParcelable(bundle: Bundle, key: String): T? =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        bundle.getParcelable(key, T::class.java)
    else
        bundle.getParcelable(key)

And you use it like this

val server = Server::class.getParcelable(bundle, "server")
  • Related