I have a method with this signature `fun translat...
# random
j
I have a method with this signature
fun translate(key: String, body: (translation: String) -> Unit)
and I need to integrate it with Java files, which requires me to
return Unit.INSTANCE;
like:
Copy code
translate("MY_KEY", translate -> {
                // Do something
                return Unit.INSTANCE;
            });
Is it possible to avoid the return statement by changing the method signature or something ?
e
use
Callable<String>
instead of
(String)  -> Unit
or add an overload (and use JvmSynthetic or JvmName to hide the kotlin one from java and Deprecated(HIDDEN) to hide the java one from kotlin)
j
sorry but, it seems that
Callable<String>
is more like
() -> String
, not
(String) -> Unit
I think I didn't understand the second comment...
e
oh right, it's
Consumer<String>
k
By the way, there's no such thing as
Unit.INSTANCE
defined in Kotlin (as far as I know).
Unit
is defined as an
object
, i.e. there is a singleton class called
Unit
(corresponding to Java's
void
) and there is only one instance of that class, also called
Unit
. You don't need to return anything in a function declared as returning
Unit
, as your function will implicitly return the instance
Unit
.
e
Copy code
@JvmName("-translate") // hide from Java
fun translate(key: String, body: (String) -> Unit)
@Deprecated(message = "for Java only", level = DeprecationLevel.HIDDEN)
fun translate(key: String, body: Consumer<String>)
Klitos, every Kotlin object (except for companions, those are a bit different) has a static Java field named INSTANCE, and it is required for Java interop in cases like this
k
Thanks. Is the field INSTANCE only accessible from Java?
e
yes
👍 1