1

can anyone help with refactoring this class to Kotlin, having trouble with generics conversation.

Model:

abstract class ViewHolderDataBinder<DM : ViewHolderDataModel,
        VH : RecyclerView.ViewHolder>(val viewType: Int) {

    abstract fun createViewHolder(parent: ViewGroup): VH

    abstract fun bindView(model: DM, holder: VH)
}

Java code that want to convert in to Kotlin:

SparseArray<ViewHolderDataBinder> viewHolderDataBinders = new SparseArray<>();

And I want to refactor it in to this

  val viewHolderDataBinders = SparseArray<ViewHolderDataBinder>()

but Kotlin requires to add type parameters in to ViewHolderDataBinder.

Is there any way to not add type parameter as It was not necessary in Java?

UPDATE

if I use private val viewHolderDataBinders = SparseArray<ViewHolderDataBinder<*, *>>()

then getting error here binder.bindView(item, holder)

it says that item and holder requires Nothing but Found .....

Antonis Radz
  • 3,036
  • 1
  • 16
  • 34
  • 2
    what is the declaration of `ViewHolderDataBinder`? Most probably Java was using the raw type, so in the type safe way the Kotlin equivalent would be `ViewHolderDataBinder<*>`. – DVarga Jun 28 '19 at 10:02
  • Please see question update – Antonis Radz Jun 28 '19 at 11:00
  • It's technically not necessary in Java, but only for ancient history reasons and using it is a bad idea: https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it. – Alexey Romanov Jun 28 '19 at 14:48

1 Answers1

0

You can use this * sign to allow any object to be added into the array.

val viewHolderDataBinders = SparseArray<ViewHolderDataBinder<*, *>>()
Seanghay
  • 1,076
  • 1
  • 11
  • 24
  • Yes, I understand that, but it is not a solution. Please read question Update – Antonis Radz Jun 28 '19 at 10:59
  • Try adding the real type to it `val viewHolderDataBinders = SparseArray>()` I think I'd work. – Seanghay Jun 28 '19 at 11:03
  • Then that part it is working, but there is other problem. My type parameters are extending other type. When trying to add something in to SparseArray with type parameters it is not working because type can be only parameter that it is extended of. See ViewHolderDataBinder declaration in question – Antonis Radz Jun 28 '19 at 11:11
  • You can cast that object to the type you want by doing `if (item is MyModelType) { doAnythingWithMyModelType(item) }` Or if you want to cast it forcefully by `val newTypeModel: MyModelType = item as MyModelType` Or cast to nullable object `val newTypeModel: MyModelType? = item as? MyModelType` . – Seanghay Jun 28 '19 at 11:17