0
0
Kotlinprogramming~15 mins

Function references (::functionName) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Function References (::functionName) in Kotlin
📖 Scenario: You are building a simple Kotlin program that processes a list of numbers. You want to reuse existing functions by passing them as references instead of writing new code.
🎯 Goal: Learn how to use function references (::functionName) to pass functions as arguments and call them in Kotlin.
📋 What You'll Learn
Create a list of integers
Create a function that doubles a number
Use a function reference (::functionName) to apply the doubling function to each number in the list
Print the resulting list
💡 Why This Matters
🌍 Real World
Function references let you reuse existing functions easily when working with collections or callbacks, making your code cleaner and more readable.
💼 Career
Understanding function references is important for Kotlin developers to write concise and maintainable code, especially in Android app development and backend services.
Progress0 / 4 steps
1
Create a list of integers
Create a variable called numbers and assign it a list containing these integers: 1, 2, 3, 4, 5.
Kotlin
Need a hint?

Use val numbers = listOf(1, 2, 3, 4, 5) to create the list.

2
Create a function that doubles a number
Create a function called double that takes an Int parameter named n and returns n * 2.
Kotlin
Need a hint?

Define the function with fun double(n: Int): Int { return n * 2 }.

3
Use a function reference to apply doubling
Create a variable called doubledNumbers and assign it the result of calling numbers.map(::double) to apply the double function to each number.
Kotlin
Need a hint?

Use val doubledNumbers = numbers.map(::double) to apply the function reference.

4
Print the resulting list
Write a println statement to display the doubledNumbers list.
Kotlin
Need a hint?

Use println(doubledNumbers) to show the doubled list.