October 2019
Intermediate to advanced
434 pages
11h 54m
English
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.ktfun 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 ...
Read now
Unlock full access