0

this is my KotlinInterface.kt

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

this is my JavaClass.java

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

        }

        @Override
        public void fun1() {

        }
    };
}

}

this is my KotlinClass.kt

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

I want to know how to return a interface with kotlin like with java ,thanks everybody

谢林志
  • 71
  • 1
  • 8

2 Answers2

2

In Kotlin, you can create an anonymous class that implements an interface like this:

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

That will give a reference to your anonymous class. You just need to return that.

Steven Schoen
  • 4,366
  • 5
  • 34
  • 65
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.
        }

    }
}
}
谢林志
  • 71
  • 1
  • 8