java - Kotlin 泛型 : Trouble migrating from Java

标签 java generics kotlin

我是 Kotlin 的新手。在尝试将 java 应用程序转换为 Kotlin 时,我遇到了以下问题,因此发布了这个问题。

这是一个模型 View 绑定(bind)器应用程序,这里是 java 接口(interface)。关键是模型和 View 是相互依赖的。

interface Model<T extends View<?>> {}

interface View<T extends Model<?>> {}

class RealModel implements Model<RealView> {}

class RealView implements View<RealModel> {}

class Binder<T extends Model<?>> {

     static <ModelT extends Model<?>> Binder<ModelT> of(View<ModelT> view) {}

}

// Application code
Binder<RealModel> binder = Binder.of(new RealView());
binder.bind(new RealModel());

我可以在 Kotlin 中做到这一点吗?

我尝试了以下
interface Model<T : View<*>> {}

ERROR: This type parameter violates the Finite Bound Restriction


interface Model<T : View<Any>> {}

ERROR: Type argument is not within its bounds: should be subtype of 'Model<*>'


interface Model<T : View<Model<*>>> {}

ERROR: This type parameter violates the Finite Bound Restriction

最佳答案

您不能在 Kotlin 中将其 1:1 转换,因为 Kotlin 限制了循环类型参数。

您可以添加一个其他语言 native 支持但 Kotlin 不支持的新类型参数来解决它,即 self类型参数(在我的示例中用 S 标识)并制作 self类型参数和其他类型参数为 协变 类型(使用 out ):

interface Model<out S : Model<S, T>, out T : View<T, S>>

interface View<out S : View<S, T>, out T : Model<T, S>>

class RealModel : Model<RealModel, RealView>

class RealView : View<RealView, RealModel>

class Binder<T : Model<*, *>> {
    companion object {
        fun <ViewT : View<*, ModelT>, ModelT : Model<ViewT, *>> of(view: ViewT): Binder<ModelT> {
            throw RuntimeException()
        }
    }
}

关于java - Kotlin 泛型 : Trouble migrating from Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676051/

相关文章:

java - 如何制作一个接受文件名并可以打印其内容的类?

java.lang.ClassCastException : org. openqa.selenium.By$ById 无法转换为 org.openqa.selenium.WebElement

java - 除非向 R.java 添加代码,否则无法运行项目

java - 将内容放入 Map<?,?> 或将 Map<String,String> 转换为 Map<?,?>

generics - 类型参数不受 impl 特征、自身类型或谓词的约束

android - 是否可以在图片上叠加图标

kotlin - kotlin:isNullOrEmpty和isNullOrBlank有什么区别?

java - 如何在 POST 请求时在 HTTP header 中设置自定义变量

java - 根据泛型接口(interface)的实现限制java中的泛型类型

java - Android:错误:-source 1.3 中不支持注释