我应该如何在 Kotlin 中设置 asList 的返回类型?

yby*_*byb 1 java collections kotlin android-studio

在此处输入图片说明 我正在学习,同时将编写的代码更改JavaKotlin.

但我对List collection使用Arrays.asListin感到困惑Java

当我将返回类型设置为 时List<String>asList会引发错误。

在 的文档中asList,返回类型是 List,为什么不允许呢?

IDE,解决办法是将返回类型改为MutableList<Array<String>>?present.. MutableList<Array<String>>?是什么意思

不仅仅是一个 MutableList,Mutable<ArrayList> 是什么意思?

List, MutableList, ArrayList.. 我不知道适合哪个

枚举类

enum class BodyType(_resourceId: Int) {
    CHEST(R.array.chest_workout_list),
    BACK(R.array.back_workout_list),
    LEG(R.array.leg_workout_list),
    SHOULDER(R.array.shoulder_workout_list),
    BICEPS(R.array.biceps_workout_list),
    TRICEPS(R.array.triceps_workout_list),
    ABS(R.array.abs_workout_list);

    @ArrayRes
    private val resourceId: Int = _resourceId


    fun getResourceId() : Int = resourceId
}
Run Code Online (Sandbox Code Playgroud)

界面

interface WorkoutListSource  {
    fun getWorkoutListByPart(type: BodyType) : ArrayList<String>?
}
Run Code Online (Sandbox Code Playgroud)

WorkoutListLocalSource.kt

class WorkoutListLocalSource(_resources: Resources) : WorkoutListSource {
    private val resource: Resources = _resources

    override fun getWorkoutListByPart(type: BodyType): ArrayList<String>? {
        Arrays.sort(resource.getStringArray(type.getResourceId()))
        return Arrays.asList(resource.getStringArray(type.getResourceId()))
    }
}
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

Arrays.asList是一个 Java stdlib 函数,它接受一vararg组参数并将它们转换为一个列表。如果你Array<String>像你正在做的那样传递它,它会返回List<Array<String>>大小为 1 的 a。

要使其与此 Java 标准库方法一起使用,您需要使用扩展运算符*。我把它分成两行以使其更清楚。

val array = resource.getStringArray(type.getResourceId())
return Arrays.asList(*array)
Run Code Online (Sandbox Code Playgroud)

在 Kotlin 中,使用 Kotlin 标准库函数会更简洁一些:

val array = resource.getStringArray(type.getResourceId())
return arrayListOf(*array)
Run Code Online (Sandbox Code Playgroud)

如果您不需要 ArrayList 并且可以返回 MutableList,则更简单,但您需要重新定义接口函数的返回类型:

return resource.getStringArray(type.getResourceId()).toMutableList()
Run Code Online (Sandbox Code Playgroud)

当您不需要从外部修改从任何获取它的函数返回的列表时,只读列表应该优先于 ArrayList/MutableList。如果您遵循良好的 OOP 原则,情况几乎总是如此。因此,如果您将接口的返回类型更改为List,则可以使用 Kotlin 标准库asList()来获取包装数组的 List,而不是像 那样复制它arrayListOf()toMutableList()或者toList()执行以下操作:

return resource.getStringArray(type.getResourceId()).asList()
Run Code Online (Sandbox Code Playgroud)

您的其他问题在此处的文档中得到解答。但基本上(Mutable)List意味着您可以将 Java 中的类型视为 MutableList 或只读列表。编译器无法区分,因为 Java 没有只读列表。一些 Java 方法返回不可变的列表,当您尝试改变它们时会抛出异常。您可以查看该方法的文档以确定将其视为 MutableList 是否安全。