Kotlin’s interoperability with Java is one of Kotlin’s greatest strengths. Kotlin calls to Java with little or no special attention, but the code that calls to Kotlin from Java is not as pretty. There will always be a time when the project switches to Kotlin and the two languages are interlocked. Recently, the first version of switching to Kotlin is coming online, so let’s summarize some of the special postures that we have encountered in Java calling Kotlin.
Different protected
- When Kotlin inherits Java, he gets the protected property directly
- Same thing when Kotlin inherited Kotlin
- But when Java inherits from Kotlin, it needs to operate on protected properties with getters and setters
- For example
[Base class definition]
[Used in Java]
- If the protected property is declared with lazy in the Kotlin parent class, it is added in Java
getValue()
(In Kotlin.value
)
Replace static Companion
- The static keyword is removed from Kotlin, and constants can be handled using companion objects
- For absolute constants, you can use the const keyword, which is called in the same way in Java as in Kotlin. Const is only available when initialized directly to a value.
- Without the const modifier, you need to use a getter in Java to get it
[Constant definition]
[Kotlin use]
Java [use]
Extension functions and top-level functions
Both of these are Kotlin features. In Kotlin calls are silky smooth, but in Java calls are normal static methods with the class name being the filename plus Kt:
[Function definition]
[Kotlin use]
Java [use]
Restore the lambda
Kotlin supports function objects where lambda can be used as arguments and return values of functions, which is also not available in Java, so calling such methods in Java becomes an anonymous inner class (the class name is called FunctionX, where X is a number for the number of arguments) :
[Define a function that accepts lambda]
[Kotlin use]
Java [use]
The Invoke method is lambda’s content function, proving that Kotlin’s implementation of lambda still defines an interface. There is an additional performance overhead to consider when using lambda, and use inline to optimize performance whenever possible.
conclusion
Java calls to Kotlin are not very common, after all I believe that after using Kotlin, you will not want to use Java. In this particular case, Kotlin’s new project introduces some of the old Java activities, which really can’t hurt without comparison. Again, Kotlin, use it, cool it, use it (Amway Face)
The number of words is a little small, there is a chance to complete the details of other intermodulation, so I added a (1). Any questions please leave a comment. RUA.