Kotlin 中的集合(List中没有了addAll())

为什么讲这个呢,集合还需要再老生常谈吗?,作为一个从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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值