Kotlin Keywords Reference 🎯

beginner
22 min

Kotlin Keywords Reference 🎯

Welcome to our comprehensive guide on Kotlin Keywords! This tutorial is designed for both beginners and intermediate learners, focusing on practical knowledge with real-world examples. Let's dive into the world of Kotlin programming language.

Understanding Kotlin Keywords 📝

Kotlin keywords are special words used to define program structures, control flow, and data types. They are essential for writing a correct and efficient Kotlin program.

Basic Kotlin Keywords ✅

Val and Var 💡

Val and Var are used to declare variables. The main difference is that Val is used for immutable variables (once assigned, cannot be changed), while Var is for mutable variables (can be changed).

kotlin
// Declaring a constant (immutable) variable using Val val myConstant: Int = 10 // Declaring a mutable variable using Var var myMutable: Int = 10 myMutable = 20 // This is valid as myMutable is mutable

Fun 💡

Fun is not a keyword, but it is used to define functions in Kotlin.

kotlin
fun greet(name: String): String { return "Hello, $name!" } // Calling the function val greeting = greet("World") print(greeting) // Output: Hello, World!

When 💡

The When keyword is used for conditional statements in Kotlin.

kotlin
fun findEvenOdd(number: Int) { when (number % 2) { 0 -> print("Even") 1 -> print("Odd") } } // Calling the function findEvenOdd(10) // Output: Even findEvenOdd(11) // Output: Odd

Advanced Kotlin Keywords (Optional) 💡

Inf and NaN 💡

Inf represents infinity (positive or negative), and NaN represents Not-a-Number (a special floating-point value representing an undefined or unrepresentable mathematical value).

kotlin
val positiveInfinity = Double.POSITIVE_INFINITY val negativeInfinity = Double.NEGATIVE_INFINITY val notANumber = Double.NaN

In 💡

The In keyword is used in range checks.

kotlin
fun isInRange(number: Int, start: Int, end: Int) = number in start..end // Calling the function println(isInRange(10, 5, 20)) // Output: true println(isInRange(30, 5, 20)) // Output: false

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of the `Val` keyword in Kotlin?

We hope this guide helps you understand Kotlin keywords better. Keep coding and happy learning! 🚀🚀