Class functions

We can add functions to a class to add functionality and to interact with that class. Like in Java, we can refer to a function on a class as a method. Methods are tied to the instance of the class they are associated with.

Defining a method is fundamentally the same as defining a top-level function, with the primary exception being that a method is declared within a class body. In the following example, we've defined a Person class that has a single method named printName():

class Person(
val firstName: String,
val lastName: String) {

fun printName() {
println("$firstName $lastName")
}
}

Note that the definition of printName doesn't look any different than the other top-level functions we've defined in this chapter.

To invoke the printName function, we must first instantiate an instance of Person and then reference that instance before calling printName:

fun main(args: Array<String>) {
val nate = Person("Nate", "Ebel")
nate.printName()
}

Visibility modifiers for methods are similar to top-level functions, but must also take into account the visibility of the class itself. 

If we make the Person class private, we will no longer be able to call printName() even though it is a public method:

private class Person(
val firstName: String,
val lastName: String) {

fun printName() {
println("$firstName $lastName")
}
}

Because Person was made private in the previous snippet, the following code no longer compiles:

fun main(args: Array<String>) {
val nate = Person("Nate", "Ebel")
nate.printName() // error: class is private in file
}

This is just a small look at methods in Kotlin. Methods on classes and objects are covered in more detail in Chapter 5Modeling Real-World Data. In the next section, we'll introduce the concept of functions defined within other functions.