1

I am trying to convert from java to kotlin. The current java interface is something like this:

interface MyInterface {
    void foo(int x, int y);
}

MyInterface testing = (int a, int b) -> System.out.print("TESTING");

My current kotlin conversion is:

interface MyInterface {
    fun foo(x:Int, y:Int)
}

val kotlinConversion = object: MyInterface {
    override fun foo(x: Int, y: Int) {
        println("TESTING")
    }
}

Is there a way to write the variable kotlinConversion such that it is similar to the one in java without having to override the function?

3
  • Do you need it to be an interface? A function type could potentially work just as well. Commented Dec 5, 2017 at 3:25
  • 3
    I think in order for any of us to answer, we need a better idea of your use case. What you have in Kotlin is not how one would do it in Kotlin. On the other hand, if you have a functional interface in Java, you can use a Lambda, and it will get cast/processed correctly. If it's all Kotlin code, then as chris said, you'll likely want a function type. Something like val kotlinConversion: (Int, Int) -> Unit = {x,y -> println("TESTING") } Commented Dec 5, 2017 at 3:28
  • 2
    This has been discussed here in kotlin forum. discuss.kotlinlang.org/t/kotlin-sam-traits-as-lambda-functions/… @Mikezx6r answer is the suggested solution. Commented Dec 5, 2017 at 4:10

1 Answer 1

3

Without override the function you can directly use like this way

var kotlinConversion = { a: Int, b: Int -> print("TESTING") }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.