有没有一种方法可以获取继承Kotlin中的接口(或另一个类)的对象类型?

时间:2018-06-24 14:54:36

标签: kotlin

我有一个带有方法的接口IMyInterface

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 (
    }

或者得到一种实现抽象类的类。

2 个答案:

答案 0 :(得分:1)

您想做的事情是不可能的。您希望编译器“神奇地”弄清模板参数是什么...考虑一下;怎么知道-IMyInterface可能有无限子集。在您的界面中并没有暗示模板类型<T>甚至是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
}

答案 1 :(得分:0)

Thomas Cook的答案没有涵盖另一个问题:即使有可能,您也至少会以两种方式遇到子类型的重大问题。

让我们假设一个关键字Self表示您想要的关键字和

interface IMyInterface{
    fun myMethod(thing: Self): Unit
}

问题1:您有一个val x: IMyInterface = ...,您可以将什么传递给x.myMethod?当然,没有任何IMyInterface会达到目的。但是,唯一可以保证与x具有相同具体类型的是... x(假设没有Self返回方法)。

问题2:添加class MySubClass : MyClass。它必须有override fun myMethod(thing: MySubClass),对吗?但是它还必须从override fun myMethod(thing: MyClass)继承MyClass