Like in Java, and other OOP languages, Kotlin classes can contain member functions (methods). To add a method to a class, we can simply define a function within the class body. Here, we've added a method named printStudentInfo to the Student class:
class Student(_firstName: String, val lastName: String) {
...
fun printStudentInfo() {
println("id:$id -> $firstName $lastName")
}
}
We can then invoke the printStudentInfo() method on an instance of the Student class by referencing the instance of Student, followed by a . and then the method name and any required arguments, as in the following example:
fun main(args: Array<String>) {
val student = Student("Nate", "Ebel")
student.printStudentInfo()
}
To change the visibility of a method, we can add a visibility modifier before the fun keyword such as the following:
class Student(_firstName: String, val lastName: String) {
...
private fun printStudentInfo() {
println("id:$id -> $firstName $lastName")
}
}
By adding the private modifier, the printStudentInfo() method is now private to the Student class and inaccessible outside the implementation of Student. We'll look at visibility modifiers more closely later in this chapter. In the next section, we're going to look more closely at how we can customize the construction of our class instances.