【问题标题】:How to return a interface like javawith Kotlin [duplicate]如何用Kotlin返回像java这样的接口[重复]
【发布时间】:2017-06-21 23:51:28
【问题描述】:

这是我的 KotlinInterface.kt

interface KotlinInterface {
fun fun1()
fun fun2()
}

这是我的 JavaClass.java

public class JavaClass {
public KotlinInterface test() {
    return new KotlinInterface() {
        @Override
        public void fun2() {

        }

        @Override
        public void fun1() {

        }
    };
}

}

这是我的 KotlinClass.kt

class KotlinClass {
    fun test():KotlinInterface{
        return KotlinInterface{
            //how to return like java
        }
    }
}

我想知道如何用 kotlin 像 java 一样返回接口,谢谢大家

【问题讨论】:

    标签: java kotlin


    【解决方案1】:

    在 Kotlin 中,您可以创建一个实现如下接口的匿名类:

    object : KotlinInterface {
        override fun fun1() {
            ...
        }
        override fun fun2() {
            ...
        }
    }
    

    这将引用您的匿名类。你只需要返回那个。

    【讨论】:

    • 感谢您的帮助
    【解决方案2】:
    class KotlinClass {
    fun test():KotlinInterface{
        return object :KotlinInterface{
            override fun fun1() {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
    
            override fun fun2() {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
    
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多