Kotlin from Java
Just as Java can be used seamlessly in Kotlin, Kotlin can just as easily be used from your Java programs.
Top-level functions
The JVM does not support top-level functions. Therefore, to make them work with Java, the Kotlin compiler creates a Java class with the name of the package. The functions are then defined as Java methods on this class, which must be instantiated before use.
For example, consider the following top-level function:
package com.packt.chapter4 fun cube(n: Int): Int = n * n * n
If this is given, the Kotlin compiler will generate a class called com.packt.chapter4.Chapter4
with functions as static members. To use this from Java, we would access this function as we would access any other static method:
import com.packt.chapter4.Chapter4; ...
Get Programming Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.