Combining Functions and Control Flow
Sveip for å vise menyen
Combining functions with control flow statements such as loops and conditionals lets you write more flexible and powerful Kotlin programs. When you place logic inside functions and use for or while loops along with if statements, your code becomes easier to read, test, and reuse. You can process collections of data, make decisions, and return results all within a single function. The following example shows how to structure code that uses a function to process a list, applies a loop to handle each item, and uses an if statement to perform conditional logic on each element.
Main.kt
1234567891011121314151617package com.example fun filterEvenNumbers(numbers: List<Int>): List<Int> { val result = mutableListOf<Int>() for (number in numbers) { if (number % 2 == 0) { result.add(number) } } return result } fun main() { val input = listOf(1, 2, 3, 4, 5, 6) val evens = filterEvenNumbers(input) println("Even numbers: $evens") }
In this code, the filterEvenNumbers function takes a list of integers as a parameter. Inside the function, a mutable list called result is created to hold the even numbers. The for loop goes through each number in the input list. The if statement checks if the current number is even by using the modulo operator (%). If the condition is true, the number is added to the result list. After the loop finishes, the function returns the list of even numbers. The main function demonstrates how to call filterEvenNumbers and print the result. This structure shows how you can combine functions, loops, and conditionals to process and filter data in Kotlin.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår