有没有办法获取继承Kotlin中接口(或其他类)的对象类型?
我有一个接口IMyInterface和一个方法有没有办法获取继承Kotlin中接口(或其他类)的对象类型?,kotlin,Kotlin,我有一个接口IMyInterface和一个方法 fun myMethod(thing: T){} 我也有一节课 class MyClass : IMyInterface{} 我想要的是,当我实现接口的成员时,它会自动将类型T设置为MyClass。有办法吗? 因此,与其写作 interface IMyInterface <T>{ fun myMethod(thing: T){} } class MyClass: IMyInterface<MyClass>{
fun myMethod(thing: T){}
我也有一节课
class MyClass : IMyInterface{}
我想要的是,当我实现接口的成员时,它会自动将类型T设置为MyClass。有办法吗?
因此,与其写作
interface IMyInterface <T>{
fun myMethod(thing: T){}
}
class MyClass: IMyInterface<MyClass>{
override fun myMethod(thing: MyClass){} // <<<-- the type is set because I explicitly set it above
}
我想要这样的东西:
interface IMyInterface{
fun myMethod(thing: T){}
}
class MyClass: IMyInterface{
override fun myMethod(thing: MyClass){} // <<<-- the template type <T> of the interface is resolved by the compiler by checking what type I provided in method signature (
}
或者得到一种实现抽象类的类。您想要做的是不可能的。您希望编译器神奇地找出模板参数是什么。。。想想看;它怎么知道呢?IMyInterface有一个潜在的无限子集。在您的界面中,模板类型甚至不是IMyInterface类型,因此它可以是任何类型 下面是关于这个问题的另一个角度,可以清楚地说明为什么编译器不能这样做:
// The same interface as your example, but with extra method
interface IMyInterface{
fun myMethod(thing: T){}
fun myOtherMethod(thing: T){}
}
// The same implementation as before, except the extra method is overridden with a different type than the first method
class MyClass: IMyInterface{
// the template type <T> of the interface is resolved by the compiler by
// checking what type I provided in method signature (this is what you want compiler to do)
override fun myMethod(thing: MyClass){}
// Uh oh! How does the copmpiler resolve this? We just figured out that <T> was my class.
// So this method won't compile... why not just tell entire class what <T> is
// rather than trying to make all method signatures match up so the compiler can "infer" the type???
override fun myOtherMethod(thing: MyOtherClass) {}
}
class MyOtherClass : IMyInterface {
override fun myMethod(thing: MyOtherClass) = this
override fun myOtherMethod(thing: MyOtherClass) = this
}
Thomas Cook的回答没有涉及到另一个问题:即使这是可能的,你也会在至少两个方面遇到子类型的重大问题 让我们假设一个关键字Self,它表示您想要什么,并且
interface IMyInterface{
fun myMethod(thing: Self): Unit
}
问题1:您有一个valx:IMyInterface=。。。您可以将什么传递给x.myMethod?当然不是任何形式的对话,那会破坏目的。但唯一能保证与x具有相同混凝土类型的是。。。假设没有自返回方法
问题2:添加类MySubClass:MyClass。它一定很有趣myMethodthing:MySubClass,对吧?但它也必须从MyClass继承myMethodthing:MyClass 您不能这样做-如果接口有泛型类型参数,则必须在实现它时提供它。@zsmb13获取实现抽象类的类的类型怎么样?我已经更新了我的问题。谢谢,有道理!不用担心——我花了很长时间才在Kotlin/Java/CS中研究泛型,有时当我累了的时候,我仍然会大脑放屁,并开始认为编译器可以创造奇迹-