0

I m doing something about the android DiffUtil and i want to make it generic.I want to pass the getter function (itemGetter) when creating the class A but when i declare the type of itemGetter in the constructor. I don't know how to declare it. ()->V is incorrect. because I can't doing something like item.itemGetter() The Class T is about a class with a itemGetter

class T() {
    val item = ....
    
    fun itemGetter(): String {
        return this.item
    }
}


class A<T,V>(var item1 :T , var item2:T ,var itemGetter: ()->V){
    fun comparing(item1: T,item2:T): Boolean {
        return item1.itemGetter()===item2.itemGetter()
    }
}

Thanks

update specific Example

class DiffCallBackUtil<T>(var oldList: ArrayList<T>, var newList: ArrayList<T> ) : DiffUtil.Callback() {


   override fun areItemsTheSame(oldi: Int, newi: Int): Boolean {
        return oldList[oldi] === newList[newi]

    }
}

Because we check the are itemsTheSame require to compare the name or id or something instance in the model T, Therefore, i need pass a getter as function in the Model T to the DiffCallBackUtil. Therefore, i can invoke oldList[oldi].getName()===newList[newi].getName()

yuk
  • 49
  • 8
  • What do you wanted to do exactly? – Animesh Sahu Jun 26 '20 at 04:56
  • i want to know how to declare itemGetter: ()->V , because ()->V is false. i want to make it that item1.itemGetter() is available – yuk Jun 26 '20 at 04:58
  • Can you elaborate a bit more, I still couldn't understand... What is the use of itemGetter? And if you declared it in the class why do you want it as a lambda? – Animesh Sahu Jun 26 '20 at 05:03
  • 1
    Your question is especially confusing because your classes have one-letter names just like the conventional names of generic types. It’s really hard to see what you’re trying to do. Also your function parameters are shadowing the class properties. – Tenfour04 Jun 26 '20 at 05:06
  • i have update the question. . Thanks – yuk Jun 26 '20 at 05:08
  • 1
    I think you need type `T.()->V` Also, in Kotlin a getter function is redundant unless it requires a parameter. The property already has a getter that you can customize if you want to do something other than returning the backing field. – Tenfour04 Jun 26 '20 at 05:13

0 Answers0