Function properties

We can add function properties to our defined classes as well. These properties follow the same rules as regular function variables, but are scoped to instances of their enclosing class. In the following code, we've defined a GreetingViewModel class that has a greetingProvider property, which is a function that takes in no arguments and returns a string:

class GreetingViewModel {
var greetingProvider: (() -> String) = { "Hello" }
}

We might then modify the class to greet a user in response to some event. We've done this in the following example by adding a greetUser() method:

class GreetingViewModel {
var greetingProvider: (() -> String) = { "Hello" }

private fun greetUser() {
println(greetingProvider())
}
}

We could then customize the printed greeting by assigning a new function to the greetingProvider property of a given instance of GreetingViewModel as follows:

fun main(args: Array<String>) {
val viewModel = GreetingViewModel()
viewModel.greetingProvider = { "Hey" }
}

In this case, we've reassigned viewModel.greetingProvider to a function that returns "Hey" instead of the "Hello" default.