Kotlin Tutorial

Kotlin Classes

Class functions:

Recall the regular functions; you also can use functions in a class to perform some specific task.

Create a function inside the class.

Example:

				
					class Human(var name: String,var role: String) {

   fun eat(dish: String) {
       println("I ate $dish")
   }
}

				
			

Let’s create an object and get access to this function.

				
					val h1 = Human("Steve Jobs", "Founder")

println("I'm ${h1.name}; ${h1.role} of Apple")

// accessing function

h1.eat("Pizza")
				
			

The code above will outputs:

				
					I'm Steve Jobs; Founder of Apple
I ate Pizza

				
			

Tip: A function inside a class is often called “class function” or “member function”. 

There can be multiple functions in a single class.

Example:

				
					class Human(var name: String,var role: String) {

   fun eat(dish: String) {
       println("I ate $dish")
   }

   fun sleep() {
       println("Sleeping mode ON...")
   }

   fun code() {
       println("Let's CODE...")
   }

   // REPEAT -->
}

				
			

Create object, access to the functions and finally print them:

				
					val h1 = Human("Steve Jobs", "Founder")

println("I'm ${h1.name}; ${h1.role} of Apple")

// accessing function

h1.eat("Pizza")
h1.sleep()
h1.code()

				
			

The code above will outputs:

				
					I'm Steve Jobs; Founder of Apple
I ate Pizza
Sleeping mode ON...
Let's CODE…