Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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; 
    Chapter4.cube(3); 

We can even change the name of the class the compiler creates by using an annotation:

    @file:JvmName("MathUtils") 
    package com.packt.chapter4 
    fun cube...