To Documents

Introduction to Kotlin

Kotlin Hello World

The main Function

Datatypes, Variables and Constants

Control Structures: Decision

Control Structures: Repetition

Methods

Arrays

Lists

Classes

  1. Like a Java class, a Kotlin class contains instance variables and instance methods.
  2. Unlike Java, getters and setters can be created automatically by the compiler.
  3. Example 13: create a Dog class defined by this UML diagram:
    +----------------------------+
    |             Dog            | 
    +----------------------------+
    | - name : String {get}      |
    | - breed : String {get}     |
    | - age : Int {get, set}     |
    | - weight : Int { get, set} |
    +----------------------------+
    | + haveBirthday( )          |
    | + bark( ) : String         |
    +----------------------------+
    
  4. Here is the Kotlin code for the Dog class and a main method to test it:
    //--------------------------------------
    // Example 13.
    // Source code file: Dog.kt
    // The fields name and breed cannot be changed, so
    // they are defined with val; age and weight can be
    // changed, so they are defined with var.
    class Dog(val name : String, val breed : String,
              var age : Int, var weight : Int) {
        
        fun haveBirthday( ) {
            age++;
        }
    
        fun bark( ) : String {
            if (weight >= 20) {
                return "Woof"
            }
            else {
                return "Yip"
            } 
        }
    
        override fun toString( ) : String {
            return "$name;$breed;$age;$weight"
        }
    }
    //--------------------------------------
    // Example 13.
    // Source code file: Test1.kt
    fun main( ) {
        var dog1 = Dog("Sparky", "Dachshund", 3, 12)
        println(dog1)
        println("Name: ${dog1.name}")
        println("Breed: ${dog1.breed}")
        println("Age: ${dog1.age}")
        println("Weight: ${dog1.weight}")
        dog1.haveBirthday( )
        println(dog1.age)
        println(dog1.bark( ))
        dog1.weight = 22
        println(dog1.bark( ))
    }
    
  5. Example 14. Another example is the Point class. It contains the dist method that measures the distance from the current Point object (x, y) to the origin (0, 0). The equals method returns true, which indicates that the two points this and other are equal if
          this.x == other.x

    and
          this.y == other.y
    .
    The toString method of the Point class outputs the point in ordered pair notation, for example (3.2, 9.0).
    // Example 14
    // Source code file: Point.kt
    class Point(var x : Float, var y : Float) : Comparable<Point> {
    
        fun dist( ) : Float {
            var x2 : Double = (x * x).toDouble( )
            var y2 : Double = (y * y).toDouble( )
            return Math.sqrt(x2 + y2).toFloat( )
        }
    
        override fun compareTo(other : Point) : Int {
            if(this.dist( ) > other.dist( )) return 1
            else if(this.dist( ) < other.dist( )) return -1
            else return 0
        }
    
        fun equals(other : Point) : Boolean {
            return this.x == other.x && this.y == other.y
        }
    
        override fun toString( ) : String {
            return "($x, $y)"
        }
    }
    ----------------------------------------
    // Example 14.
    // Source code file: Test1.kt
    fun main( ) {
    
        // Create array of four Point objects. The f suffix
        // makes the constants of type Float.
        var arr = arrayOf(Point(3.4f, 7.5f), Point(1.9f, 2.6f),
        Point(0.3f, 0.7f), Point(1.5f, 6.1f))
    
        // Sort points in order from closest to the origin 
        // to furthese from origin.
        arr.sort( )
    
        // Print sorted points.
        for(p in arr) {
            print("$p ${p.dist( )} ")
        }
    }
    
  6. Example 15. This example is inspired by Griffiths and Griffiths, Head First Kotlin, A Brain Friendly Guide, 2019, O'Reilly
  7. Sometimes we want to include instance variables in our class that are not initialized with constructor parameters; sometimes we want to include custom getters and setters in our class. Here is an example that does this:
    //--------------------------------------
    // Example 15.
    // Source code file: Dog.kt
    
    // Parameters defined in the class header are passed
    // in to a class object via the constructor, but they
    // do not immediately define instance variables because 
    // val or var are not used.
    class Dog(name_param: String, breed_param: String,
              weight_param: Int) {
    
        // Define name field to be read only; ensure that
        // it is it non-empty.
        var name = if (name_param.equals("")) "Unknown" else name_param
    
        // Define breed field. Define getter to return
        // the breed in all caps.
        val breed = breed_param
            get( ) = field.uppercase( )
    
        // Define weight field.  Ensure that weight
        // is non-negative.
        var weight = if (weight_param > 0) weight_param else 0
            set(value) {
                field = if (value > 0) value else 0
            }
    
        // toString method
        override fun toString( ) : String {
            return "$name;$breed;$weight"
        }
    }
    
    //--------------------------------------
    // Example 15.
    // Source code file: Test1.kt
    fun main( ) {
        var dog1 = Dog("Bentley", "Bernese Mountain Dog", 115)
        println(dog1)
        println(dog1.name + " " + dog1.breed + " " + dog1.weight)
    
        var dog2 = Dog("", "Cocker Spaniel", -20)
        println(dog2)
        println(dog2.name + " " + dog2.breed + " " + dog2.weight)
        dog2.weight = 85
        println(dog2.weight)
    }
    
  8. Why is wrong with these lines of code for defining a setter?
    var weight = weight_param
        set(value) {
           if (value > 0) weight = value
        }
    }
  9. To the Dog class in Example 14, add and test this getter:
    var weightInKilos : Int
        get( ) = weight / 2.2046
    
  10. To the Dog class in Example 14, add and test this property that is not initialized with a constructor parameter:
    var vaccinated = false;
    
    When a Dog object is created, it is initially unvaccinated. To vaccinate the dog, the use the setter for vaccinated:
    dog1.vaccinated = true
    

More Collections

Inheritance

Nullable Types

Anonymous and Lambda Functions

A Kotlin Android App: TempConverter5