Bird
Raised Fist0
Android Kotlinmobile~20 mins

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

Choose your learning style10 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

Practice

(1/5)
1. What is a lambda function in Kotlin?
val sum = { a: Int, b: Int -> a + b }
easy
A. A function that must have a name and cannot be stored
B. An unnamed function that can be stored in a variable
C. A special class for storing data
D. A type of loop for repeating code

Solution

  1. Step 1: Understand lambda syntax

    The code { a: Int, b: Int -> a + b } defines a function without a name.
  2. Step 2: Identify lambda characteristics

    This function is stored in the variable sum, showing it is unnamed but reusable.
  3. Final Answer:

    An unnamed function that can be stored in a variable -> Option B
  4. Quick Check:

    Lambda = unnamed function stored in variable [OK]
Hint: Lambdas have no name and are assigned to variables [OK]
Common Mistakes:
  • Thinking lambdas must have names
  • Confusing lambdas with classes
  • Assuming lambdas are loops
2. Which of the following is the correct syntax to declare a lambda that takes no parameters and returns a String "Hello"?
easy
A. val greet = fun() { return "Hello" }
B. val greet = () -> "Hello"
C. val greet = { -> "Hello"
D. val greet = { "Hello" }

Solution

  1. Step 1: Review lambda syntax for no parameters

    Lambdas with no parameters use { expression } syntax.
  2. 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.
  3. Final Answer:

    val greet = { "Hello" } -> Option D
  4. Quick Check:

    No-parameter lambda = { value } [OK]
Hint: Use { expression } for lambdas with no parameters [OK]
Common Mistakes:
  • Missing closing brace in lambda
  • Confusing lambda with function type syntax
  • Using fun keyword inside lambda
3. What is the output of this Kotlin code?
val multiply = { x: Int, y: Int -> x * y }
println(multiply(3, 4))
medium
A. 7
B. 34
C. 12
D. Error

Solution

  1. Step 1: Understand the lambda function

    The lambda { x: Int, y: Int -> x * y } multiplies two integers.
  2. Step 2: Calculate the result of multiply(3, 4)

    3 * 4 equals 12, so the printed output is 12.
  3. Final Answer:

    12 -> Option C
  4. Quick Check:

    3 * 4 = 12 [OK]
Hint: Multiply inputs inside lambda to get output [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Concatenating numbers as strings
  • Expecting syntax error
4. Identify the error in this Kotlin lambda declaration:
val greet = { name: String ->
  println("Hello, " + name)
}
medium
A. No error, this is valid syntax
B. Cannot use println inside lambda
C. Missing return type declaration
D. Lambda must return a value, println returns Unit

Solution

  1. Step 1: Check lambda syntax

    The lambda takes a String parameter and calls println, which is allowed.
  2. Step 2: Confirm return type flexibility

    Lambdas can return Unit (like void), so no return type declaration is needed.
  3. Final Answer:

    No error, this is valid syntax -> Option A
  4. Quick Check:

    Lambda with println is valid [OK]
Hint: Lambdas can return Unit; println is allowed [OK]
Common Mistakes:
  • Expecting return type declaration
  • Thinking println is disallowed
  • Confusing Unit with error
5. You want to filter a list of numbers to keep only even numbers using a lambda. Which code correctly does this?
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter( /* fill here */ )
println(evens)
hard
A. numbers.filter { it % 2 == 0 }
B. numbers.filter { x -> x / 2 == 0 }
C. numbers.filter { it % 2 = 0 }
D. numbers.filter { it & 2 == 0 }

Solution

  1. Step 1: Understand filtering with lambda

    The filter lambda should return true for even numbers using modulo operator.
  2. Step 2: Evaluate each option

    numbers.filter { it % 2 == 0 } correctly uses it % 2 == 0. numbers.filter { x -> x / 2 == 0 } uses division instead of modulo, C uses assignment (=) instead of comparison (==), A uses bitwise AND incorrectly.
  3. Final Answer:

    numbers.filter { it % 2 == 0 } -> Option A
  4. Quick Check:

    Filter even numbers with modulo == 0 [OK]
Hint: Use it % 2 == 0 to check even numbers in filter [OK]
Common Mistakes:
  • Using = instead of == for comparison
  • Using division instead of modulo
  • Misusing bitwise operators
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard