【问题标题】:Android Kotlin cannot use list.sort() with lambdaAndroid Kotlin 不能将 list.sort() 与 lambda 一起使用
【发布时间】:2018-02-01 10:33:16
【问题描述】:

有一个字符串列表,过滤器直接使用 lambda 表达式

val list= ArrayList<String>()
list.add("eee")
list.add("888")
list.add("ccc")

list.filter({it.length > 0})

// this passing function works too
list.filter(fun(it) = it.length > 0)

定义为取lambda函数类型:(T) -&gt; Boolean

public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
    return filterTo(ArrayList<T>(), predicate)
}

但类似的语法不适用于sort()。它要求使用 sortWith 代替。不明白为什么不能像 filter() 调用那样直接传递 lambda 表达式。

有人能解释一下为什么sort() 不能直接对 lambda 函数使用类似的语法吗?

list.sort({ first: String, second: String ->
    first.compareTo(second)
})

list.sort 定义如下,同样采用 lambda 函数:(T, T) -&gt; Int:

public inline fun <T> MutableList<T>.sort(comparison: (T, T) -> Int): Unit = throw NotImplementedError()

但它给出了错误“using sort((T, T) -> Int) : Unit is an error Use sortWith(Comparator(comparison)) instead

sort()sortWith() 在定义中具有相同的返回类型 Unit

对于sortWith(),它必须通过比较器,例如:

list.sortWith(Comparator { first, second ->
    first.compareTo(second)
})

定义为:

@kotlin.jvm.JvmVersion
public fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit {
    if (size > 1) java.util.Collections.sort(this, comparator)
}

Arrays.sort 也可以使用与filter() 相同的语法,并且直接使用 lambda 函数

var listStr = TextUtils.join(", ", list);
Arrays.sort(arrayOf(listStr)) { first: String, second: String ->
    first.compareTo(second)
}

Arrays.sort 定义为:

public static <T> void sort(T[] a, Comparator<? super T> c) {
    throw new RuntimeException("Stub!");
}

【问题讨论】:

    标签: android sorting lambda kotlin


    【解决方案1】:

    因为sort 已弃用并标记为DeprecationLevel.ERROR

    @Deprecated("Use sortWith(Comparator(comparison)) instead.", ReplaceWith("this.sortWith(Comparator(comparison))"), level = DeprecationLevel.ERROR)
    @JvmVersion
    @kotlin.internal.InlineOnly
    @Suppress("UNUSED_PARAMETER")
    public inline fun <T> MutableList<T>.sort(comparison: (T, T) -> Int): Unit = throw NotImplementedError()
    

    这就是您收到错误并且编译器要求使用sortWith 的原因。

    【讨论】:

    • 感谢@Bob!我想问题更多是关于为什么 kotlin 将这种“已弃用”的排序放在那里并且不允许您使用。集合类型上的函数最好有类似的调用语法。
    猜你喜欢
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多