Defining Functions in Kotlin
Pyyhkäise näyttääksesi valikon
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
12345678910package 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.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme