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);
    
  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( ))
    }
    
  3. Test these Kotlin List or MutableList methods: filter, map, forEach. These methods each take a lambda function parameter.
  4. Check that the last parameter of the JPC Button element is named content, which accepts a lambda function. Verify that this parameter can be written in training lambda notation.
  5. 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

Practice Problems

  1. Run the JPCEx ClickCounter2 Example.  Click the button several times, then rotate the emulator. Notice that the click count is reset to 0.  In a JPC app, how can we save the count in a Bundle and restore it when the app is recreated and restarted?
  2. For the TheRaven Example, we used the Scanner class, which comes from Java. Test these alternative Kotlin versions for reading from a file in the raw folder:
    // Read the entire file into a string:
    val s = inputStream.bufferedReader().use { 
        it.readText( ) 
    }
    
    // Read the file line by line:
    var s = ""
    inputStream.bufferedReader( ).useLines { 
        lines -> lines.forEach { 
            line -> s += line + "\n"
        } 
    } 
    

Android Platform