在Kotlin中,MyClass具有List成员,而Builder具有获取列表的功能。
但是在Java代码中调用建造者的时候
fun dataList(dataList: List)
它会导致编译错误
List<> cannot be applied to ArrayList<>
.
从反编译的代码中,它显示的列表是
kotlin.collections.List<>
.
如何用JAVA调用列表?
data class MyClass(
val context: Context,
val dataList: List = emptyList(),
) {
private constructor(builder: Builder) : this(builder.context, builder.dataList)
class Builder {
private var context: Context? = null
private var dataList: List = emptyList()
fun context(context: Context) = apply { this.context = context }
fun dataList(dataList: List) = apply { this.dataList = dataList }
fun build() = MyClass(this)
}
}
用Java语言
ArrayList theDataList = new ArrayList();
theDataList.add(new Data())
MyClass myClass = new MyClass.Builder()
.context(appContext)
.dataList(theDataList) //<== error
.build();
错误是:
dataList(Java.util.List) in Builder cannot be applied to dataList(Java.util.ArrayList)
在Java代码中,如果单击DATALISTHER(),它会打开下面的反编译代码,并且似乎抱怨
fun dataList(dataList: kotlin.collections.List)
:
public final data class Data public constructor(context: android.content.Context,
dataList: kotlin.collections.List /* = compiled code */) {
public final val context: android.content.Context /* compiled code */
public final val dataList: kotlin.collections.List /* compiled code */
public final operator fun component1(): android.content.Context { /* compiled code */ }
public final operator fun component2(): kotlin.collections.List { /* compiled code */ }
public final class Builder public constructor() {
private final var context: android.content.Context? /* compiled code */
private final var dataList: kotlin.collections.List /* compiled code */
... ...
public final fun dataList(dataList: kotlin.collections.List): com.model.MyClass.Builder { /* compiled code */ }
... ...
public final fun build(): com.model.Data { /* compiled code */ }
}