Kotlin Class Examples

  1. Class without a Constructor but with default variable (or properties or data)
    [box type="info" align="" class="" width=""]In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.[/box]
    class Person {
         val name : String = "Peter" // Default Variable 
         var age : Int = 30 // Default Variable
    }
    fun main (args: Array<String>){
         val person = Person() // this line tell kotlin to instantiate a new object from 'Person' class
         person.age = 33 //accessing our 'Person' property
         person.name = "Peterr"// this won't compile and can't be re-assigned because 'val' keyword makes it immutable
    }
    
  2. Class without a Constructor but with properties (or variables or data) and Methods
    fun main (args: Array<String>){
       val person = Person() // this line tell kotlin to instantiate a new object from 'Person' class
       person.speak() // Hello!
       person.greet("Opeyemi") // Hello Opeyemi!
    }
    class Person {
       val name : String = "Peter"
       var age : Int = 30
    
       fun speak(){
          println("Hello!")
       }
       fun greet (name: String){
          println("Hello $name!")
       }
       fun getYearOfBirth () : Int {
          return 2018 - age // don't do this in production code! 
          /* do this instead 
             val cal : Calendar = Calendar.getInstance()
             return cal.get(Calendar.YEAR) - age
          */
       }
       fun getYearOfBirth() = 2018 - age //this a more concise way of writing the function get yearOfBirth
    }
  3.  Class with Constructor, variable passed in and using the init block - initialization block. Initialization block would be called only ONCE, when the object is created and it defines what is supposed to happen during object creation. We can also use the init block to get values passed into our constructor and assign it to  member variable.
    class ClassExample{
        fun main (args: Array<String>){
            val person = Person("Jack", 21) // new 'Person' object with name 'Jack', age '21'
            person.speak() // Hello!
            val birthYear = person.getYearOfBirth() 
            println(birthYear) // 1997 
            // Initialization block would print 'Object Was Created' to console
        }
    class Person (name: String ,  age: Int){
            val nameVal : String // member variable
            var ageVar : Int // member variable
            init {
                println("Object Was Created")
                nameVal = name
                ageVar = age
            }
            fun speak(){
                println("Hello!")
            }
            fun birthday(){
                ageVar++ //increment age by 1. ageVar = ageVar+1
            }
            fun getYearOfBirth() :Int{
                val cal : Calendar = Calendar.getInstance()
                return cal.get(Calendar.YEAR) - ageVar
            }
        }
    }
  4. Class with Constructor, variable passed in and without using the init block. If you think about it, the above code in number 3 is much similar to java code and we end up writing more boiler plate code which kotlin is trying to eliminate in the first place. Don't fret kotlin offers a more concise way to write (number 3) code.
    class ClassExample {
        fun main(args: Array<String>) {
            val person = Person("Jack", 21) // new 'Person' object with name 'Jack', age '21'
            var birthYear : Int = person.getYearOfBirth() 
            println(birthYear) // 1997 
            person.age = 22 // we re-assigned the age
            birthYear = person.getYearOfBirth() // 1996
            person.speak() // Hello!
            
        }
    
        class Person(val name: String, var age: Int) {
            fun speak() {
                println("Hello")
            }
    
            fun birthday() {
                age++
            }
    
            fun getYearOfBirth() = Calendar.getInstance().get(Calendar.YEAR) - age
            
        }
    }
    Introducing the val and var keyword in our constructor eliminated the need for an Initialization block, member variables and boiler plate code. Sweet? yeah!
  5.  Class with default value. Default value is within the constructor. This allows us to overload constructors pretty easily
    [box type="info" align="" class="" width=""]It's common to overload constructors - define multiple constructors which differ in number and/or types of parameters. For example, exact price of house within an area is common, in Java additional constructor could be defined which takes only the price parameter but in kotlin you can do that by specifying a default value within the constructor[/box]
    class ClassExample {
        fun main(args: Array<String>) {
            val orangeHouse = House("Orange", 20.0, 60.0)
            val redHouse = House(price = 151, width = 20.1, color = "Red", height = 59.5) // using Name parameter
    // we can change the order of our parameters as long as we correctly type parameter names 
    // this makes our code more readable and flexible
           
            orangeHouse.print() // House(color='Orange', height=20.0m, width=60.0m, price=$130k)
            redHouse.print() // House(color='Red', height=59.5m, width=20.1m, price=$151k)
    
        }
    
        class House(var color: String, val height: Double, val width: Double, val price: Int = 130) { 
          // default house price of $130k
            fun print() {
                println("House(color='$color', height=${height}m, width=${width}m, price=$${price}k)")
            }
        }
    }

Comments

Popular posts from this blog

How to select Multiple Item in RecyclerView in Android

Android Clipboard Listener - How to Know when User copies a text in Android

Kotlin ArrayList and Loops Example