2

I'm trying to understand why I cannot use my inline function defined in a Kotlin file in my Java code?

Project details

Kotlin: 1.5.20 - Java: 15.0.1

Mixed code (Java + Kotlin). I have same package structure both in Java & Kotlin as below:

com.app.company.util.Util.java

com.app.company.util.Util.kt

In Util.kt I have an inline function as below:

val commonMapper = jacksonObjectMapper()

inline fun <reified T> parseJson(content: String): T {
   return commonMapper.readValue(content)
}

I noticed that since I have the same name Util for both Java class and Kotlin file, If I want to refer to the Kotlin file I have to use UtilKt. I found this by decompiling the Kotlin file.

Interestingly, only commonMapper is exposed by getCommonMapper() method not parseJson.

Could someone please help me understand why parseJson is not visible from Java?

Vahid
  • 1,625
  • 1
  • 18
  • 33
  • 1
    This is really interesting. Just to narrow it down a bit, it's not an issue with inline functions specifically, but has to do with the reified parameter. As soon as that's removed everything works as expected. – Henry Twist Jul 02 '21 at 14:40
  • 2
    If the issue is reified parameters, then [this](https://stackoverflow.com/questions/42741780/how-can-i-call-kotlin-methods-with-reified-generics-from-java) is probably a better dup. – Silvio Mayolo Jul 02 '21 at 14:42
  • 1
    That defintiely answers the question. The current duplicate doesn't seem to address the issue, as the inline function by itself works fine. – Henry Twist Jul 02 '21 at 14:45
  • @SilvioMayolo I added it, but the first question says that calling inline functions from Java is not possible at all. – Mark Rotteveel Jul 02 '21 at 14:45
  • It does seem to say that @MarkRotteveel, but using `UtilKt.parseJson(...)` (as in the OP's question) does indeed work. – Henry Twist Jul 02 '21 at 14:47
  • @MarkRotteveel *Calling* inline functions is fine. They'll just behave like ordinary functions. The point that answer is making is that they won't magically inline in Java like they do in Kotlin. The issue is `reified`, not `inline`. – Silvio Mayolo Jul 02 '21 at 19:56

0 Answers0