为什么讲这个呢,集合还需要再老生常谈吗?,作为一个从java转向kotlin的人来说,集合还不是手到擒来。这里主要讲讲二者之间使用的区别,避免采坑。下面我们从实际案例入手:
想必大多数Android 开发者都有遇到过分页加载列表的需求吧,比如我们会写一个添加数据的代码
private List<MessageItem> list = null;
public MessageAdapter(List<MessageItem> list) {
this.list = list;
}
public void appendData(List<MessageItem> list) {//必须是追加
this.list.addAll(list);
notifyDataSetChanged();
}
使用java 编写 it work fine
但是使用kotlin编写的时候,按照我们以前的习惯我们往往会这么写
class MessageAdapter(var list: List<MessageItem>) {
fun appendData(list: List<MessageItem>) {
this.list.addAll(list)
notifyDataSetChanged()
}
}
不好意思,直接报错,说没有这个方法,点击查看源码如下
/**
* A generic ordered collection of elements. Methods in this interface support only read-only access to the list;
* read/write access is supported through the [MutableList] interface.
* @param E the type of elements contained in the list. The list is covariant on its element type.
*/
public interface List<out E> : Collection<E> {
// Query Operations
override val size: Int
override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean
override fun iterator(): Iterator<E>
// Bulk Operations
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
// Positional Access Operations
/**
* Returns the element at the specified index in the list.
*/
public operator fun get(index: Int): E
// Search Operations
/**
* Retu