Lesson 29: OOP – Properties – Methods SET and GET in Kotlin

We have seen that when we define a public property we can access its content to modify it or to consult it from where we defined an object.

To a property, we can associate a method called SET at the time it is assigned a value and another method called GET when accessing the content of the property.

These methods are optional and allow us to validate the data to be assigned to the property or the return value.

When these methods are not implemented the same compiler creates these two methods by default.

Problem 1

Declare a class called person with two properties that store the person’s name and age. In the property name store always capitalized the name and when it recovers its value return it in parentheses, also control that you can not enter an age with negative value, in that case store a zero.

Project125 – Main.kt

class Person {
    var name: String = ""
        set (value) {
            field = value.toUpperCase ()
        }
        get () {
            return "(" + field + ")"
        }

    var age: Int = 0
        set (value) {
            if (value >= 0)
                field = value
            else
                field = 0
        }
}

fun main (parameter: Array <String>) {
    val person1 = Person ()
    person1.name = "juan"
    person1.age = 23
    println (person1.name) // Prints: (JUAN)
    println (person1.age) // Prints: 23
    
    person1.age = -50
    println (person1.age) // Prints: 0
}

First we define the property type name String:

    Var name: String = ""

In the immediately following line we define the set method (which does not carry the fun keyword) and has a parameter that does not indicate the type because it is of the same type as the name property. Within the set method we can modify the contents of the property name using the keyword field (in this problem we store the data that arrives but converted to capital letters):

    Set (value) { 
        field = value.toUpperCase () 
    }

In case the property implements the get method we also do it before or after the set method if it has it:

    Get () { 
        return "(" + field + ")" 
    }

The old property only implements the set method where we verify if the parameter that receives is negative we store in the property the value 0 but we store the value as it arrives.

It is also very important to understand that when we define an object of the person class and assign a value to a property, we are actually executing a method:

    Val person1 = Person () 
    person1.name = "juan" // the set method of the property name is executed

After this assignment in the name property the String “JUAN” was stored in upper case since that does the set method.

In the assignment:

    Person1.age = 23

The number 23 is stored since it is greater than or equal to zero.

We can check the values of the properties:

    Println (person1.name) // Prints: (JUAN) 
    println (person1.age) // Prints: 23

If we try to set a value less than zero in the property age:

    Person1.age= -50

Then it is not loaded since in the set method we verify the data that arrives and load in case the negative value is zero:

    Println (person1.age) // Prints: 0

Problems proposed

  • Make a class that represents an Employee. Define properties as your name and your salary.
    Do not allow a negative amount to be charged to your salary.
    Encode the print method in the class.
  • Raise a class called Given. Defining a property called a value that allows loading a value between 1 and 6, if a value that does not fall within this range must be loaded 1.
    Define two methods, one that generates a random number between 1 and 6 and another one that Print.
    The constructor arrives at the initial value that the die must have (try to send the number 7)
Solution

class Employee (var name: String, salary: Double) {

    var salary: Double = 0.0
        set (value) {
            if (value <0)
                field = 0.0
            else
                field = value
        }

    init {
        this.salary = salary
    }

    fun print ( ) {
        println ("$name has a salary of $salary")
    }
}

fun main (parameter: Array <String>) {
    val employee1 = Employee ("John", 12000.50)
    employee1.print()
    val employee2 = Employee("Ana", -1200.0)
    employee2.print()
}
 Proecto127
class given (value: Int) {
    var value: Int = 1
    set (value) {
        if (value >= 1 && value <= 6)
        field = value
        else
        field = 1
    }

    init {
        this.value = value
    }

    fun throww () {
        value = ((Math.random () * 6) + 1) .toInt ()
    }

    fun print () = println ("Value of data: $value")
}

fun main (parameter: Array <String>) {
    val given1 = given (7)
    given1.print ()
    given1.throww ()
    given1.print ()
}

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

No ratings yet.

Please rate this

Leave a Reply

Your email address will not be published. Required fields are marked *