Hello guys, how can I run kotlin extensions from j...
# getting-started
q
Hello guys, how can I run kotlin extensions from java?
m
quver:
FileNameKt.someExtension(receiver);
r
To extend on that, you can put an
@file:JvmName("SomeUtils")
annotation at the very top of the file, to switch the default name
FileNameKt
for any Class name you want, to make them look like very standard Util-functions to Java code.
q
I have
Copy code
@file:JvmName("AndroidExtensions")

fun Context.dpToPx(dp: Float): Int = (dp * resources.displayMetrics.density + 0.5f).toInt()
and then I try use it in java
Copy code
AndroidExtensions.dpToPx(2f);
and got error:
Copy code
dpToPx
(android.content.Context,
float)
in AndroidExtensions cannot be applied
to
(float)
m
You have to pass Context (receiver) to the method.
r
Yeah, you have to pass the receiver of the extension function in as its first argument. So if you would do this in kotlin:
ctx.dpToPx(2f)
you'd do this in Java:
AndroidExtensions.dpToPx(ctx, 2f)
q
@miha-x64 @robin Thanks a lot!
@miha-x64 You already help me a few time! Thanks! 🙂
simple smile 1