Top-level functions
Another thing we can observe in a simple Hello, World!
program is that the main
function is not located inside any class. In Chapter 2, Laying a Foundation, we already mentioned that Kotlin can define various entities at the top level. A function that is defined at the top level is called a top-level function. Here is an example of one of them:
// Test.kt package com.example fun printTwo() { print(2) }
Top-level functions can be used all around the code (assuming that they are public, which is the default visibility modifier). We can call them in the same way as functions from the local context. To access a top-level function, we need to explicitly import it into a file by using the import
statement. Functions are available in the code hint list in Android Studio, so imports are automatically added when a function is selected (used). As an example, let's see a top-level function defined in Test.kt
and use it inside the Main.kt
file:
//...