LoginSignup
0
3

More than 5 years have passed since last update.

Kotlinのコールバックブロック付きのメソッドをJavaから呼ぶ

Posted at

kotlinのコールバックブロック付きのメソッドをJavaコードから実行する時には、下記のようにする必要があった。
下記のような場合、Java側で
return Unit.INSTANCE;
がないとコンパイルエラーだが、
「ラムだ式の戻り値の型が不整合です」と言われるだけで、どうやればよいか悩んだので、投稿。

kotlin

class KotlinClass {

    fun loadItems(itemIds: List<String>,
                  complete: (isSuccess: Boolean, itemList: List<Item>) -> Unit) {
        /*  何かしらの処理 */
        complete(true, itemList)
    }
}


java(呼び出し側)

kotlinClass.loadItems(itemIds, (isSuccess, items) -> {
                    /*  何かしらの処理 */

                    //注意:最後に Unit.INSTANCE を返す必要がある
                    return Unit.INSTANCE;
                })

理由

kotlinでは、メソッドの戻り値がないときも、実際は、return Unit を省略しているという扱いになっていて、Javaでそれと互換性を保つために return Unit.INSTANCE; しないとならないらしい。

参考:http://stackoverflow.com/questions/37828790/why-do-i-have-to-return-unit-instance-when-implementing-in-java-a-kotlin-functio

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3