Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Defining Functions in Kotlin | Functions and Control Flow
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Introduction to Kotlin

bookDefining Functions in Kotlin

Scorri per mostrare il menu

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

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 1
some-alt