当前正在开发一个应用程序,我决定用Kotlin编写。但是,该应用程序与最初使用Java编写的单独模块进行交互。
我有以下Kotlin数据类:
data class BasketItem(
@SerializedName("id") var id :String ,
@SerializedName("parentID") var parentID: String ,
@SerializedName("barcode") var barcode : String ,
@SerializedName("guid") var guid : String ,
@SerializedName("functionalName") var functionalName : String ,
@SerializedName("posPosition") var posPosition : Int ,
@SerializedName("itemvalue") var itemvalue : ItemValue ,
@SerializedName("quantity") var quantity :Int )
{
constructor(): this("","","","","",0,ItemValue(),0)
}
data class ItemValue(
@SerializedName("costpriceexcl") var costpriceexcl: Double ,
@SerializedName("costpriceincl") var costpriceincl :Double ,
@SerializedName("sellingpriceExc") var sellingpriceExc : Double ,
@SerializedName("sellingpriceIncl") var sellingpriceIncl : Double ,
@SerializedName("vatAmount") var vatAmount : Double )
{
constructor():this (0.0,0.0,0.0,0.0,0.0)
}
var basketitems: ArrayList<BasketItem> = ArrayList()
我试图将此ArrayList传递给用Java编写的模块。我创建了具有相同参数的等效类
缩短的Java等效类。我没有包括构造函数,getter和setter。
public class BasketItem
{
public String id;
public String parentID;
public String barcode;
public String guid;
public String functionalName;
public Integer posPosition;
public ItemValue itemvalue ;
public Integer quantity ;
}
public class ItemValue
{
private Double costpriceexcl;
private Double costpriceincl;
private Double sellingpriceExc;
private Double sellingpriceIncl;
private Double vatAmount;
public ItemValue()
{
}
public ItemValue(Double costpriceexcl, Double costpriceincl, Double sellingpriceExc, Double sellingpriceIncl, Double vatAmount)
{
this.costpriceexcl = costpriceexcl;
this.costpriceincl = costpriceincl;
this.sellingpriceExc = sellingpriceExc;
this.sellingpriceIncl = sellingpriceIncl;
this.vatAmount = vatAmount;
}
}
当我尝试将Arraylist从Kotlin端传递到Java端时。我收到以下错误:
类型不匹配:推断的类型为
kotlin.collections.ArrayList<com.rewards.Model.Models.BasketItem>
/* = java.util.ArrayList<com.rewards.Model.Models.BasketItem> */
but java.util.ArrayList<com.data.entities.POS.BasketItem> was expected
答案 0 :(得分:1)
类型不同。这就像尝试将List<String>
传递给List<Integer>
一样。
即试图将“ Hello”,“ World”列表放入期望值为1,2,3的列表中
仅通过Kotlin或Java中的引用,您不能强迫一种类型成为另一种类型。
如果我们假设Kotlin模块依赖于Java模块。
仅在Java模块中创建BasketItem
,然后将其作为列表类型(无论是Kotlin还是Java)。
var basketitems: ArrayList<BasketItem> = ArrayList()
List<BasketItem> basketItems = new ArrayList<>();