lan*_*nyf 1 kotlin function-reference
具有类成员函数,例如:
private fun getData1(uuid:String): IData? {
...
}
private fun getData2(uuid:String): IData? {
...
}
private fun getData3(uuid:String): IData? {
...
}
Run Code Online (Sandbox Code Playgroud)
并想放入一个函数引用数组:
var funArray = ArrayList<(uuid: String) -> IData?> (
this::getData1,
this::getData2,
this::getData3)
Run Code Online (Sandbox Code Playgroud)
它不编译:
None of the following functions can be called with the arguments
supplied:
public final fun <E> <init>(): kotlin.collections.ArrayList<(uuid: String) -> IData?> /* = java.util.ArrayList<(uuid: String) -> IData?> */ defined in kotlin.collections.ArrayList ...
Run Code Online (Sandbox Code Playgroud)
如果这样做:
var funArray: ArrayList<(uuid: String) -> IData?> = ArrayList<(uuid: String) -> IData?>(3)
funArray[0] = this::getData1 //<== crash at here
funArray[1] = this::getData2
funArray[2] = this::getData3
Run Code Online (Sandbox Code Playgroud)
异常崩溃
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Run Code Online (Sandbox Code Playgroud)
如何将函数引用放入数组中?
第一次尝试失败,因为ArrayList没有构造函数接受(变量参数列表)值。
ArrayList您可以通过替换为listOf()(或者,如果您需要可变性, )来获得几乎相同的效果mutableListOf(),因为这确实需要一个可变参数列表:
var functions = listOf<(uuid: String) -> IData?>(\n this::getData1, \n this::getData2, \n this::getData3)\nRun Code Online (Sandbox Code Playgroud)\n\n这也许是最自然的解决方案。\xc2\xa0 (但是,mutableListOf()仅保证返回一个MutableList实现;它可能不是一个ArrayList。)
第二次尝试失败,因为它正在构建一个空列表。
\n\n(它使用的ArrayList 构造函数采用一个名为 的参数initialCapacity;它确保列表可以采用至少 3 个元素,而无需重新分配其数组,但其初始大小为零。)
也许造成混淆是因为虽然你说你 \xe2\x80\x98would 放入一个函数引用数组\xe2\x80\x99,但你正在创建一个List,而不是一个Array.
(该类ArrayList是接口的实现List,恰好在内部使用数组。\xc2\xa0 这遵循将实现类命名为 的 Java 约定<Implementation><Interface>。)
如果您需要创建一个实际的数组,您可以arrayOf()在第一个示例中使用:
var functions = arrayOf<(uuid: String) -> IData?>(\n this::getData1, \n this::getData2, \n this::getData3)\nRun Code Online (Sandbox Code Playgroud)\n\n在 Kotlin 中,列表可能比数组使用更广泛,因为它们更灵活。\xc2\xa0(您可以在具有不同特征的许多不同实现之间进行选择。\xc2\xa0 它们与泛型配合使用效果更好;例如,您可以创建一个List泛型类型。\xc2\xa0 你可以使它们不可变。\xc2\xa0\xc2\xa0当然,如果它们是可变的,它们可以增长和收缩。)
但数组也有其一席之地,特别是如果性能很重要,您需要与使用数组的代码进行互操作,和/或大小是固定的。
\n| 归档时间: |
|
| 查看次数: |
2050 次 |
| 最近记录: |