Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 6 / 68

Writing a Function

In this lesson you will learn the basic way to define a function in Kotlin so you can reuse the same logic over and over. This is for anyone searching for "Kotlin functions how to use".

You define a function with fun name(param: Type): ReturnType. Bundling frequently used work under a name means you only have to call it to run it.

The sample code has greet take a name: String parameter and return a greeting, with the return type stated explicitly as : String. Like a recipe, once you have named a set of steps you can reproduce the same result whenever you need it.

A common stumbling block for beginners is how the parameter and return types are written. Kotlin writes paramName: Type and puts the return type after the function name with a colon, and that distinctive ordering takes some getting used to.

In real-world development, gathering shared logic into functions reduces duplication and means a fix only has to be made in one place.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)