Simple Calculator Enter first number: [ ] Enter second number: [ ] Choose operation: ( ) Add ( ) Subtract ( ) Multiply ( ) Divide [ Calculate ] Result: ________
Functions and lambdas in Android Kotlin - Mini App: Build & Ship
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 } }
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.
Simple Calculator Enter first number: [ 12.5 ] Enter second number: [ 3.0 ] Choose operation: ( ) Add ( ) Subtract ( ) Multiply (x) ( ) Divide [ Calculate ] Result: 37.5
Practice
val sum = { a: Int, b: Int -> a + b }Solution
Step 1: Understand lambda syntax
The code{ a: Int, b: Int -> a + b }defines a function without a name.Step 2: Identify lambda characteristics
This function is stored in the variablesum, showing it is unnamed but reusable.Final Answer:
An unnamed function that can be stored in a variable -> Option BQuick Check:
Lambda = unnamed function stored in variable [OK]
- Thinking lambdas must have names
- Confusing lambdas with classes
- Assuming lambdas are loops
Solution
Step 1: Review lambda syntax for no parameters
Lambdas with no parameters use{ expression }syntax.Step 2: Check each option
val greet = { "Hello" } correctly uses{ "Hello" }. val greet = { -> "Hello" missing closing brace, B is function type syntax, D is a named function.Final Answer:
val greet = { "Hello" } -> Option DQuick Check:
No-parameter lambda = { value } [OK]
- Missing closing brace in lambda
- Confusing lambda with function type syntax
- Using fun keyword inside lambda
val multiply = { x: Int, y: Int -> x * y }
println(multiply(3, 4))Solution
Step 1: Understand the lambda function
The lambda{ x: Int, y: Int -> x * y }multiplies two integers.Step 2: Calculate the result of multiply(3, 4)
3 * 4 equals 12, so the printed output is 12.Final Answer:
12 -> Option CQuick Check:
3 * 4 = 12 [OK]
- Adding instead of multiplying
- Concatenating numbers as strings
- Expecting syntax error
val greet = { name: String ->
println("Hello, " + name)
}Solution
Step 1: Check lambda syntax
The lambda takes a String parameter and calls println, which is allowed.Step 2: Confirm return type flexibility
Lambdas can return Unit (like void), so no return type declaration is needed.Final Answer:
No error, this is valid syntax -> Option AQuick Check:
Lambda with println is valid [OK]
- Expecting return type declaration
- Thinking println is disallowed
- Confusing Unit with error
val numbers = listOf(1, 2, 3, 4, 5, 6) val evens = numbers.filter( /* fill here */ ) println(evens)
Solution
Step 1: Understand filtering with lambda
The filter lambda should return true for even numbers using modulo operator.Step 2: Evaluate each option
numbers.filter { it % 2 == 0 } correctly usesit % 2 == 0. numbers.filter { x -> x / 2 == 0 } uses division instead of modulo, C uses assignment (=) instead of comparison (==), A uses bitwise AND incorrectly.Final Answer:
numbers.filter { it % 2 == 0 } -> Option AQuick Check:
Filter even numbers with modulo == 0 [OK]
- Using = instead of == for comparison
- Using division instead of modulo
- Misusing bitwise operators
Ready to prove it?
Pass the test and this pattern moves unknown
