Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Defining Functions in Kotlin | Functions and Control Flow
Introduction to Kotlin

bookDefining Functions in Kotlin

Veeg om het menu te tonen

Functions are a fundamental building block in Kotlin, allowing you to organize code into reusable pieces. A function groups a set of instructions that can be executed whenever you need them, making your code easier to read and maintain. To declare a function in Kotlin, you use the fun keyword, followed by the function name, parentheses for parameters, and curly braces for the function body. Parameters are defined inside the parentheses, each with a name and type. If the function returns a value, you specify the return type after a colon. Otherwise, the function returns Unit by default, which is similar to void in Java.

Main.kt

Main.kt

copy
12345678910
package com.example; fun addNumbers(a: Int, b: Int): Int { return a + b } fun main() { val result = addNumbers(5, 7) println("The sum is $result") }

In this example, the addNumbers function is declared with two parameters: a and b, both of type Int. The function returns an Int, as indicated by the : Int after the parameter list. Inside the function body, a and b are added together, and the result is returned using the return keyword. In the main function, addNumbers is called with the arguments 5 and 7. The result of the function call is stored in the result variable, and then printed to the console. This demonstrates how to define a function, pass arguments, receive a return value, and use the result in your program.

question mark

Which of the following is the correct way to declare a function in Kotlin that takes two Int parameters and returns their product as an Int?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 1

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 3. Hoofdstuk 1
some-alt