我遵循了教程:https://kotlinlang.org/docs/tutorials/native/mpp-ios-android.html,并成功导出了Android的jar文件和iOS的框架。之后,我想实现一些更复杂的东西。我将Android Studio Kotlin与以下代码结合使用:
Model.kt:
package org.kotlin.mpp.mobile.BusinessLogic
abstract class Model{
var _id:Long = 0
abstract fun PolymorphismTest()
}
Sales.kt:
package org.kotlin.mpp.mobile.BusinessLogic
class Sales : Model() {
init {
this._id = _counter
_counter++
}
companion object {
private var _counter: Long = 0
}
fun get_counter(): Long {
return _counter
}
private val _salesItems:MutableList<SalesItem> = ArrayList()
fun SalesItems(): MutableList<SalesItem> {
return _salesItems
}
fun TotalAmount():Double
{
var totalAmount:Double = 0.0
for(aSalesItem in _salesItems)
{
totalAmount += aSalesItem.SubTotal()
}
return totalAmount
}
fun AddSalesItem(salesItem: SalesItem)
{
this._salesItems.add(salesItem)
}
fun AddSalesItem(itemName:String, itemCode:String, quantity:Double, amount:Double )
{
val aSalesItem = SalesItem()
aSalesItem._itemCode = itemCode
aSalesItem._itemName = itemName
aSalesItem._quantity = quantity
aSalesItem._amount = amount
this.AddSalesItem(aSalesItem)
}
fun ToString(): String {
return "Sales: $this._id"
}
override fun PolymorphismTest() {
println("This is method from Sales")
}
}
SalesItem.kt:
package org.kotlin.mpp.mobile.BusinessLogic
class SalesItem : Model() {
init {
this._id = _counter
_counter++
}
companion object {
private var _counter: Long = 0
}
fun get_counter(): Long {
return _counter
}
var _sales: Sales? = null
var _amount:Double = 0.toDouble()
var _quantity:Double = 0.toDouble()
fun SubTotal(): Double {
return _amount * _quantity
}
var _itemName:String? = null
var _itemCode:String? = null
fun Sales():Sales?{
return _sales
}
fun SalesItem(sales:Sales)
{
_sales = sales
this._id = _counter
_counter++
}
fun ToString(): String {
return "Sales: $this._id"
}
override fun PolymorphismTest() {
println("This is method from SalesItem")
}
}
我将这些代码导出到框架中,然后导入Xcode并使用Swift进行调用
ViewController.swift
import UIKit
import SharedCode
class ViewController: UIViewController{
override func viewDidLoad(){
super.viewDidLoad()
print("Creating Sales Object")
let sales = Sales() //error here
}
}
之后,我遇到了
的错误kotlin.Error,kotlin.RuntimeException和子类的实例不会从Kotlin传播到Objective-C / Swift。 如果方法具有或继承@Throws批注,则其他异常可以作为NSError传播。 未捕获的Kotlin异常:kotlin.native.concurrent.InvalidMutabilityException:冻结的org.kotlin.mpp.mobile.BusinessLogic.Sales.Companion@228b588的突变尝试 在0 SharedCode处
答案 0 :(得分:0)
Kotlin / Native具有不同的线程模型。这个想法是必须冻结对象的实例才能从所有线程访问它。有.freeze()
个扩展方法。
默认情况下,object Smth
也被冻结。在代码狙击手中,伴随对象中具有可变字段。
可能的解决方法是用您明确创建的普通类替换伴侣对象
https://kotlinlang.org/docs/reference/native/concurrency.html#concurrency-in-kotlinnative
https://kotlinlang.org/docs/reference/native/immutability.html#immutability-in-kotlinnative