Home > Back-end >  KOTLIN: Can I Call Multiple Class Methods Outside Apply block and Difference in Calling Methods Insi
KOTLIN: Can I Call Multiple Class Methods Outside Apply block and Difference in Calling Methods Insi

Time:04-29

package com.example.learning

fun main(args: Array<String>) {

    var person = Person("Ramu", 51, 50000F, 7.5F)

    person.apply{
        name = "Sam"
        id = 1
        details()
    }.details()
}

Q1)What is the difference in calling details or any class method inside and outside the apply block?

Q2)Here in the apply block can I call multiple class methods at once like calling Salary and Details at the same time outside the apply block with .details()&.salary()?

class Person(var name: String, var id: Int, var sal: Float, var salRaise: Float){
    fun details(){
        println("The name of the person is $name with id $id and salary if $sal")
    }

    fun salary(): Float{
        sal *= salRaise
        return sal
    }
}

CodePudding user response:

apply is just a convenience method so you don't have to write person every time.

This:

person.apply{
    name = "Sam"
    id = 1
    details()
}

is the same as doing:

person.name = "Sam"
person.id = 1
person.details()

I'm not sure what you mean by your second question. You ask how to call those 2 methods outside a apply? Just do

person.details()
person.salary()

There's another benefit to using apply. If person could be null you could do person?.apply to only change those fields in the case the person is not null. So this for example:

fun changePerson(person : Person?) {
    person?.apply{
        name = "Sam"
        id = 1
        details()
    }
}

is the same as

fun changePerson(person : Person?) {
    if (person != null) {
        person.name = "Sam"
        person.id = 1
        person.details()
    }
}

EDIT:

If you want to be able to chain the salary() after a details() you could do it by making this change:

class Person(var name: String, var id: Int, var sal: Float, var salRaise: Float){
    fun details() : Person{
        println("The name of the person is $name with id $id and salary if $sal")
        return this
    }

    fun salary(): Float{
        sal *= salRaise
        return sal
    }
}

then you could do this for example:

person.apply{
    name = "Sam"
    id = 1
}.details().salary()
  • Related