Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Last active November 29, 2017 19:24
Show Gist options
  • Save NikolaDespotoski/fdace97a81c43007626c1cf64e7182b8 to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/fdace97a81c43007626c1cf64e7182b8 to your computer and use it in GitHub Desktop.
Kotlin operator overloading for RecyclerView operations
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