Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android kotlin method accept any object type as parameter

Tags:

android

kotlin

I want to pass 2 different object types to a method to update the view. How can I have this method accept 2 different object types and access them instead of having 2 different methods for 2 different object types.

I needed something like this -

fun updateView(object: Any<T>) {
   //Access the objects here to update the view
}
like image 694
Ma2340 Avatar asked Mar 12 '26 15:03

Ma2340


2 Answers

fun <T : Any> updateView(obj: T) {
    //Access the objects here to update the view
}

OR

fun updateView(obj: Any ?= null, obj2:Any ?= null) {
    // Access the objects here to update the view

    // pass check nullity and use which you want (or not null), other parameter will remain null

    obj?.let {
       it...
    }

    obj2?.let {
       it...
    }
}

Call

updateView(obj1, obj2)

// OR

updateView(obj2 = myObj2)
like image 79
Narek Hayrapetyan Avatar answered Mar 14 '26 19:03

Narek Hayrapetyan


You can use interfaces for this:

interface ViewInterface {
    fun action() 
}

class ObjectA : ViewInterface {...}
class ObjectB : ViewInterface {...}

fun updateView(ob: ViewInterface) {
    ob.action()
}


like image 31
papafe Avatar answered Mar 14 '26 19:03

papafe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!