To Lecture Notes

IT 372 -- May 18, 2026

Review Exercises

  1. Last week we saw that to round a Kotlin Double value to two digits after the decimal point, we could use the Java String.format method:
    val x = 3.14159265
    val s = String.format("%.2f", x);
    
    In the Kotlin playground, test this alternative version that is similar to Python:
    val x = 3.14159265
    val s = "%.2f".format(x);
    // Output: 3.14
    
  2. Unlike Java, Kotlin implements extension functions, which are a way to add instance methods to a class without using inheritance. Test this example in the Kotlin playground, which adds a dollar method to the Double class:
    fun Double.dollar( ) : String {
        return "$%.2f".format(this)
    }
    
    fun main( ) {
        var amount = 15.9576
        println(amount.dollar( ))
    }
    // Output: $15.96
    
  3. Test these Kotlin List or MutableList methods: filter, map, forEach. These methods each take a lambda function parameter. Answer:
    var animals = listOf("dog", "wolf", "pig", "skunk", "cow");
    
    // filter only keeps list items for which
    // the lambda function returns true.
    println(animals.filter { it.length == 3 });
    // Output: [dog, pig, cow]
    
    // map applies the lambda function to each item
    // in the list, forming a new list from the results.
    println(animals.map { it.uppercase( ) });
    // Output: [DOG, WOLF, PIG, SKUNK, COW]
    
    // forEach applies the lambda function to each 
    // element of the list like a for loop.
    animals.forEach { print("$it ") }
    // Output:
    dog wolf pig skunk cow 
    
  4. We know how to set up and use a JPC state variable:
    var stateValue = remember { mutableStateOf("abc") }
    ...
    // Usage
    val s = stateString.value  // <-- Getter
    stateString.value = "xyz"  // <-- Setter
    
    Try out these alternative formulations:
    // Alternative version 1:
    var stateValue by remember { mutableStateOf("abc") }
    ...
    // Usage
    val s = stateString   // <-- Getter
    stateString = "xyz"   // <-- Setter
    
    // Alternative version 2:
    val (value, setValue) = remember { mutableStateOf("abc") } 
    ...
    // Usage
    val s = value     // <-- Getter
    setValue("xyz")   // <-- Setter
    
    Alternative version 1 seems to be the most popular.

More About the Any Class

Data Classes

JetPack Compose Examples