0
0
KotlinHow-ToBeginner · 3 min read

How to Create Function in Kotlin: Simple Guide

In Kotlin, you create a function using the fun keyword followed by the function name, parentheses for parameters, and a body enclosed in braces. For example, fun greet() { println("Hello") } defines a simple function that prints a message.
📐

Syntax

A Kotlin function starts with the fun keyword, followed by the function name, parentheses () which may include parameters, and a body inside curly braces { }. You can also specify the return type after the parentheses using a colon :.

  • fun: keyword to declare a function
  • functionName: the name you give your function
  • (parameters): input values the function can take (optional)
  • : ReturnType: type of value the function returns (optional)
  • { ... }: code block that runs when the function is called
kotlin
fun functionName(parameter1: Type1, parameter2: Type2): ReturnType {
    // function body
}
💻

Example

This example shows a function named greet that prints a greeting message. It takes a name parameter of type String and prints a personalized message.

kotlin
fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")
}
Output
Hello, Alice!
⚠️

Common Pitfalls

Beginners often forget to use the fun keyword or miss the parentheses after the function name. Another common mistake is not specifying the return type when the function returns a value, or forgetting to return a value.

Also, using incorrect parameter syntax or missing curly braces can cause errors.

kotlin
/* Wrong: Missing fun keyword and parentheses */
// greet { println("Hi") }

/* Correct: */
fun greet() {
    println("Hi")
}
📊

Quick Reference

ElementDescriptionExample
funKeyword to declare a functionfun
functionNameName of the functiongreet
parametersInputs inside parenthesesname: String
return typeType of value returned: Int
bodyCode inside curly braces{ println("Hi") }

Key Takeaways

Use the fun keyword followed by the function name and parentheses to create a function.
Parameters go inside parentheses with their types; return type is optional if the function returns nothing.
Always include curly braces {} to define the function body.
Remember to call the function by its name with arguments if needed.
Watch out for missing fun keyword, parentheses, or curly braces which cause errors.