Classes and functions

In this section, we will have a quick look at how behaviors and functions can be implemented. We will continue with our Person class, which has three behaviors—speak, eat, and walk.

As we know, class behaviors are represented by functions. We can declare a function within the class body:

  1. Create a class with a primary constructor and add the speak() function by using fun keyword. When a function is declared in the class body, it becomes class behavior:
class Person (val name: String, var age : Int , var height : Double) {
fun speak() {
println("My name is $name , i am $age years old and I am $height feet tall")
}
}

fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
abid.speak()
}
  1. Create an object of the Person class and call the speak function using the . operator. Execute this program and check that it has the following output:

  1. Add some more behaviors (functions) in the Person class and call them in a similar fashion:
class Person (val name: String, var age : Int , var height : Double){

fun speak(){
println("My name is $name , i am $age years old and I am $height feet tall")
}

fun sleep(){
println("Zzzzzzz....")
}

fun eat(){
println("I am eating a delicious vegetarian dish")
}
}

fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
abid.speak()
abid.eat()
abid.sleep()
}

A function can also take a parameter as an argument and return some values. The greet() function takes a string variable as a parameter and displays a message on the screen, while the info() function returns a string variable with class properties:

class Person (val name: String, var age : Int , var height : Double){

fun info() : String {
return "My name is $name , i am $age years old and
I am
$height feet tall"
}

fun greet(message : String){
println("Hi I am $name.... $message")
}
}

fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
abid.greet("Nice to meet you!!!")

val text = abid.info()
println(text)
}

A class contains different functions. Each function has its own name, but Kotlin allows us to write more than one function with the same name. This technique is called function-overloading.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.62