我是 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/