0
0
Android Kotlinmobile~20 mins

Functions and lambdas in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Calculator
This screen lets the user enter two numbers and choose an operation (add, subtract, multiply, divide). It uses functions and lambdas to perform the calculation and show the result.
Target UI
Simple Calculator

Enter first number: [       ]
Enter second number: [       ]
Choose operation:
  ( ) Add
  ( ) Subtract
  ( ) Multiply
  ( ) Divide

[ Calculate ]

Result: ________
Two EditText fields for number input
RadioButtons to select one operation: Add, Subtract, Multiply, Divide
A Calculate button that triggers the calculation
Use separate functions for each operation
Use a lambda to select and call the correct function based on user choice
Display the result below the button
Starter Code
Android Kotlin
package com.example.simplecalculator

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // TODO: Find views by id
        // TODO: Set up Calculate button click listener
        // TODO: Implement functions and lambda for operations
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.simplecalculator

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val firstNumberInput = findViewById<EditText>(R.id.firstNumber)
        val secondNumberInput = findViewById<EditText>(R.id.secondNumber)
        val operationsGroup = findViewById<RadioGroup>(R.id.operationsGroup)
        val calculateButton = findViewById<Button>(R.id.calculateButton)
        val resultView = findViewById<TextView>(R.id.resultView)

        fun add(a: Double, b: Double) = a + b
        fun subtract(a: Double, b: Double) = a - b
        fun multiply(a: Double, b: Double) = a * b
        fun divide(a: Double, b: Double) = if (b != 0.0) a / b else Double.NaN

        val operationLambda: (Double, Double) -> Double = { a, b ->
            when (operationsGroup.checkedRadioButtonId) {
                R.id.addRadio -> add(a, b)
                R.id.subtractRadio -> subtract(a, b)
                R.id.multiplyRadio -> multiply(a, b)
                R.id.divideRadio -> divide(a, b)
                else -> Double.NaN
            }
        }

        calculateButton.setOnClickListener {
            val num1 = firstNumberInput.text.toString().toDoubleOrNull()
            val num2 = secondNumberInput.text.toString().toDoubleOrNull()

            if (num1 == null || num2 == null) {
                Toast.makeText(this, "Please enter valid numbers", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val result = operationLambda(num1, num2)

            if (result.isNaN()) {
                resultView.text = "Error: Cannot divide by zero"
            } else {
                resultView.text = "Result: $result"
            }
        }
    }
}

This app screen lets the user enter two numbers and pick an operation using radio buttons. We define four simple functions: add, subtract, multiply, and divide. Each takes two numbers and returns the result.

We then create a lambda called operationLambda that uses a when expression to check which radio button is selected. It calls the matching function accordingly.

When the user taps the Calculate button, we read the numbers safely using toDoubleOrNull(). If inputs are invalid, we show a toast message.

If inputs are valid, we call the lambda with the two numbers and display the result. We handle division by zero by returning Double.NaN and showing an error message.

This approach cleanly separates the operations into functions and uses a lambda to pick the right one based on user choice, demonstrating Kotlin functions and lambdas in a simple app.

Final Result
Completed Screen
Simple Calculator

Enter first number: [ 12.5    ]
Enter second number: [ 3.0     ]
Choose operation:
  ( ) Add
  ( ) Subtract
  ( ) Multiply  (x)
  ( ) Divide

[ Calculate ]

Result: 37.5
User enters numbers in the two input fields
User selects one operation radio button
User taps Calculate button
App shows the calculation result below the button
If inputs are invalid, a toast message appears
If dividing by zero, an error message is shown instead of a number
Stretch Goal
Add a Clear button that resets the input fields, clears the result, and resets the selected operation
💡 Hint
Use findViewById to get the Clear button, then set text of EditTexts and result TextView to empty strings and clear RadioGroup selection