Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Kotlin Properties with Example and How it Differs from Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 799
    Comment on it

    In Java there are fields but in Kotlin there are no fields like Java. Whatever variables we define in Kotlin class it becomes properties by default with internal implementations of it’s accessors.

     

     

    let's try to understand this feature feature by a simple example:

     

    Fields and Properties in Java

    We simply specify a Java class which has two variable fields and they are private to the class. To access these variable values, first you have to make them class property by defining getter and setter method in this class. Now, the fields describe the class and can be accessed via it’s accessors( getter and setter).

    So, in Java to convert a field to a property you have to specify the getter and setter method.

    public class Employee {
    
        private long id;
        private String name;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) { 
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    In Kotlin

    When we define any variables in Kotlin, we do not need to define getter and setter method manually because It has default internal implementation of assessors (getter and setter) method.

    class Employee {
    
        var name = "findnerd" // getter and setter is created
        var id = 1 // getter and setter is created
    }

    Example:

    In above Employee class, when name is initialized with i.e “findnerd”, using = operator, internally set(value) method is called and whenever this property is accessed the get() is invoked internally. And the same happens for id as well.

    fun main(args:Array<String>){
        var emp = Employee()
        println(emp.name) // internally get() is called
        emp.name = "arvind" // internally set(value) is called
        println(emp.name)
    
        println(emp.id)
        emp.id = 2 // internally set(value) is called
    }

    In the above code you don't have to write set() and get(), you can directly call emp.name instead of doing emp.getName() and emp.setName("arvind") in Kotlin. Things becomes much easiter to code in Kotlin.

    Kotlin Properties with Example and How it Differs from Java

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: