Top-level functions

Let's take a look at an example of how we can leverage top-level functions. In this snippet, we define a top-level function to print a greeting:

// Helpers.kt
fun
printGreeting(name: String) {
println("Hello $name")
}

This function can then be used anywhere within our Kotlin code base as follows:

printGreeting("Nate")

Calling top-level functions from Kotlin is very fluent, and has a very friendly syntax. However, calling these from Java takes a little more work. To call the top-level function from Java, we must invoke it as a static method on a generated class:

HelpersKt.printGreeting("Nate");

By default, the generated class will be named as <kotlin filename>Kt. So in this case, the function was defined in Helpers.kt and the generated class is named HelpersKt.