Kotlin allows defining functions in many contexts. We can define functions at the top level, as members (inside class
, interface
, and so on), and inside other functions (local function). Consider the following example of the definition of a local function:
fun printTwoThreeTimes() { fun printThree() { // 1 print(3) } printThree() // 2 printThree() // 2 }
printThree
is a local function, because it is located inside another function.- Local functions are not accessible from outside the function they were declared in.
Elements accessible inside local functions don't have to be passed from enclosing functions as arguments because they are accessible directly. For example:
fun loadUsers(ids: List<Int>) { var downloaded: List<User> = emptyList() fun printLog(comment: String) { Log.i("loadUsers (with ids $ids): $comment\nDownloaded: ...