首页 > 解决方案 > Kotlin/Native 与 Swift 的互操作性:使用具有相同签名的两个方法生成的接口

问题描述

我有一个 Kotlin 多平台项目,它使用 CoreBluetooth 库在 iOS 设备上执行蓝牙操作。我在获取外围设备断开回调时遇到了一些问题。仔细检查后,我看到生成的CBCentralManagerDelegateProtocol接口(我重写)有两个具有相同签名的方法。

@kotlin.commonizer.ObjCCallable public open expect fun centralManager(central: platform.CoreBluetooth.CBCentralManager, didFailToConnectPeripheral: platform.CoreBluetooth.CBPeripheral, error: platform.Foundation.NSError?): kotlin.Unit { /* compiled code */ }

@kotlin.commonizer.ObjCCallable public open expect fun centralManager(central: platform.CoreBluetooth.CBCentralManager, didDisconnectPeripheral: platform.CoreBluetooth.CBPeripheral, error: platform.Foundation.NSError?): kotlin.Unit { /* compiled code */ }

因此,我只能覆盖其中一种方法。我的问题是我在这里遗漏了什么吗?就像一种覆盖这两种方法的方法。

标签: kotlinkotlin-multiplatformkotlin-native

解决方案


在 kotlin 中,您不能声明具有相同签名的两个函数,仅在参数名称上有所不同。但是在 ObjC 中你可以。

要支持此互操作,您可以使用@Suppress("CONFLICTING_OVERLOADS"),如文档中所述。

要使用冲突的 Kotlin 签名覆盖不同的方法,可以向类添加 @Suppress("CONFLICTING_OVERLOADS") 注释。

@Suppress("CONFLICTING_OVERLOADS", "PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun centralManager(
    central: CBCentralManager,
    didFailToConnectPeripheral: CBPeripheral,
    error: NSError?
) {
}

@Suppress("CONFLICTING_OVERLOADS", "PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun centralManager(
    central: CBCentralManager,
    didDisconnectPeripheral: CBPeripheral,
    error: NSError?
) {
}

推荐阅读