Last active
November 29, 2017 19:24
-
-
Save NikolaDespotoski/fdace97a81c43007626c1cf64e7182b8 to your computer and use it in GitHub Desktop.
Kotlin operator overloading for RecyclerView operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class BaseBindableAdapter<T, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() { | |
internal var data: MutableList<T> = mutableListOf() | |
override fun onBindViewHolder(holder: VH, position: Int) { | |
val bindable = holder as BindableViewHolder<T> | |
bindable.bindViewHolder(data[position]) | |
} | |
override fun getItemCount(): Int = data.size | |
operator fun plusAssign(newData: Collection<T>) { | |
data = newData.toMutableList() | |
notifyDataSetChanged() | |
} | |
operator fun not() { | |
val size = data.size | |
data.clear() | |
notifyItemRangeRemoved(0, size) | |
} | |
operator fun rangeTo(newData: Collection<T>) { | |
val lastIndex = data.size - 1 | |
data.addAll(newData) | |
val newLastIndex = lastIndex + newData.size | |
notifyItemRangeInserted(lastIndex, newLastIndex) | |
} | |
operator fun minus(position: Int) { | |
data.removeAt(position)?.let { notifyItemRemoved(position) } | |
} | |
operator fun minus(value: T) { | |
val index = data.indexOf(value) | |
if (data.remove(value)) { | |
notifyItemRemoved(index) | |
} | |
} | |
operator fun plus(value: T) { | |
data.add(value) | |
notifyItemInserted(data.size - 1) | |
} | |
operator fun get(position: Int): T = data[position] | |
operator fun set(position: Int, value: T) { | |
data[position] = value | |
notifyItemChanged(position) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment