To Lecture Notes

IT 372 -- April 29, 2026

Review Exercises

  1. Look at the modifications needed in the GroceryItem Example in Exercise 2 of the April 22 Notes to restore the data when the device is rotated.
  2. Write Kotlin code to create a list with these items:
    "abc"  "def"  "hij"  "klm"
    // Answer:
    var list = listOf("abc", "def", "hij", "klm")
    
  3. Print the items in Exercise 2 with a traditional for loop and a modern for-each loop.
    // Answer:
    for(i in 0..3) {
        println(list[i])
    }
    for(item in list) {
        println(item)
    }
    
  4. When would you want to use an immutable list instead of a mutable list?
    Answer: if you know that you will not change the items in a list, use a List collection because it is safer. Otherwise, use a MutableList collection.
  5. What are some differences between Java and Kotlin classes.
    Similarities:
    Both languages can run code on the Java Virtual Machine (JVM).
    Both are statically typed, which means that variable types are checked at compile time.
    Kotlin code can be called from Java and vice-versa.
    if statements and while loops are the same in Java and Kotlin.
    Both languages are object oriented.
    Differences:
    Kotlin is more concise.
    Kotlin distinguishes between nullable and non-nullable types.
    Kotlin automatically generates getters and setters, which can be customized if needed.
  6. Which Kotlin base class is equivalent to the Java universal base class Object?
    Answer: the Any class.
  7. Create a Kotlin class A using the specs in this UML diagram. Include a main method to test this class.
    +------------------------+
    |           A            |      
    +------------------------+
    | - n : Int { get, set } |
    | - s : String { get }   |
    +------------------------+
    | + toString( ) : String |
    +------------------------+
    
    Include a custom getter for s that returns this string in uppercase. Answer:
    class A(var n : Int, sParam : String) {
        val s = sParam
            get( ) = field.uppercase( )
        override fun toString( ) : String {
            return "n: $n; s: $s"
        }
    }
    
    fun main( ) {
        val a = A(279, "abc")
        println(a)
        println("${a.n} ${a.s}")
    }
    
  8. Why is wrong with these lines of code for defining a setter?
    var weight = weight_param 
        set(value) { 
            if (value > 0) weight = value
            else weight = 0
        }
    }
    
    Answer: using weight in the setter customization causes an infinite recursion. Use field instead:
    var weight = weight_param 
        set(value) { 
            if (value > 0) field = value
            else field = 0
        }
    }
    

Introduction to Kotlin