If you want to create an instance of anonymous interface in Kotlin? Assuming the interface has only a single method you can make use of SAM.
1 2 3 | val handler = Handler<String> { println("Hello: $it"); } |
If you have a method that accepts a handler then you can even omit type arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 | fun acceptHandler(handler:Handler<String>){} acceptHandler(Handler { println("Hello: $it"); }) acceptHandler( { println("Hello: $it") }) acceptHandler { println("Hello: $it"); } |
If the interface has more than one method the syntax is a bit more verbose:
1 2 3 4 | val handler = object: Handler2<String> { override fun call(context: String?) { println("Call: $context") } override fun run(context: String?) { println("Run: $context") } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.