Thursday 21 December 2017

Kotlin: Define member functions of class

Functions in kotlin are defined using ‘fun’ keyword.

Ex:
fun square(x : Int) : Int{
         return x*x
}

Above code snippet define a function named ‘square’, it takes one argument of type Int and return the integer.

Employee.kt
class Employee {
 private var firstName: String = ""
 private var lastName: String = ""

 fun getFirstName(): String {
  return firstName
 }

 fun getLastName(): String {
  return lastName
 }

 fun setFirstName(firstName: String) {
  this.firstName = firstName
 }

 fun setLastName(lastName: String) {
  this.lastName = lastName
 }
}

Main.kt
fun main(args: Array<String>) {

 var emp1 = Employee()

 emp1.setFirstName("Chamu")
 emp1.setLastName("Gurram")

 println("firstName : ${emp1.getFirstName()}")
 println("lastName : ${emp1.getLastName()}")
}

Output
firstName : Chamu
lastName : Gurram



Previous                                                 Next                                                 Home

No comments:

Post a Comment