Kotlin Keywords, Variables and Data Types: Simple Guide with Easy Examples
Every programming language has its own set of reserved words, ways to store data, and types that shape how you write code. Kotlin is no different — but it adds its own twists. In this guide, I will explain Kotlin keywords, variables, and data types in plain words, with real examples you can run in your IDE. By the end, you will understand the foundation of Kotlin better than most beginners.
What are keywords in Kotlin?
Every programming language gives you a set of words that the compiler already understands. These words are called keywords. You cannot use them as names for your variables, functions, or classes because the compiler would get confused.
Think of keywords like reserved parking spots. Anyone can drive a car, but some spots are reserved for specific vehicles. If you park your car in a spot reserved for an ambulance, there will be trouble. Same with keywords — they belong to the language, not to you.
Kotlin is smarter than many older languages here. It does not make every keyword absolutely off-limits. Instead, it divides keywords into four types:
- Hard keywords — can never be used as identifiers
- Soft keywords — can be used as identifiers
- Modifier keywords — can be used as identifiers
- Special keywords — can also be used as identifiers
This is a big improvement over Java, where every keyword is hard. In Kotlin, you have more freedom to name things. Let's go through each type one by one.
1. Hard Keywords — the strict ones
Hard keywords are the strictest. You cannot use them as identifiers. Not as variable names. Not as function names. Not as class names. Nothing. The compiler will simply refuse.
Here is the full list of Kotlin hard keywords:
| as | break | class | continue | do |
| else | false | for | fun | if |
| in | interface | is | null | object |
| package | return | super | this | throw |
| true | try | typealias | typeof | val |
| var | when | while |
Look at some of these. class, fun, if, else, return — you have seen these before. They are the basic building blocks of Kotlin code. The compiler needs them to understand what you are trying to do.
Others like var and val are Kotlin-specific. We will talk about them in the variables section.
Try to write var class = "Math" and the compiler will throw an error. Try fun if() { } and it will fail. That is how strict hard keywords are.
Real example of a hard keyword error
fun main() {
var class = "Math" // ERROR: "class" is a hard keyword
}
The compiler says: "Expecting an element" or something similar. It does not even understand what you are trying to do because class already has a meaning.
2. Soft Keywords — the flexible ones
Soft keywords are the opposite of hard keywords. You can use them as identifiers. They only act as keywords in specific situations. In normal code, they behave like regular names.
Here is the list of soft keywords:
| by | catch | constructor | delegate | dynamic |
| get | import | init | param | property |
| receiver | set | setparam | where |
Now here is the interesting part. You can write val get = 10 and it works. You can write var set = "hello" and it works. The compiler does not complain because get and set are soft keywords.
But if you try to use get in a property declaration like val x: Int get() = 5, then it acts as a keyword. Context matters.
Real example of a soft keyword working as an identifier
fun main() {
val by = 100 // works fine, "by" is soft
val get = "value" // works fine
val set = true // works fine
println("$by, $get, $set")
}
This is one of the reasons Kotlin feels friendlier than Java. You have more freedom to name things naturally without the compiler fighting you.
3. Modifier Keywords — the behavior changers
Modifier keywords change how your code behaves. They are like switches that turn features on or off. And just like soft keywords, you can use them as identifiers if you want.
Here is the complete list:
| actual | abstract | annotation | companion | const | crossinline |
| data | enum | expect | external | final | infix |
| inline | inner | internal | lateinit | noinline | open |
| operator | out | override | private | protected | public |
| reified | sealed | suspend | tailrec | vararg |
Some of these you will use every day. data makes a class automatically generate equals(), hashCode(), and toString(). suspend marks a function that can pause and resume — the heart of Kotlin coroutines. override lets you replace a function from a parent class.
But even with all this power, you can still write val data = "hello" and it works. The compiler figures out from context whether you mean the keyword or a variable.
Real example: using a modifier keyword as a variable name
fun main() {
val data = "This works" // "data" is a modifier keyword
val open = false // "open" is a modifier keyword
val private = 42 // "private" is a modifier keyword
println("$data, $open, $private")
}
This flexibility is one of the things that makes Kotlin pleasant to write. You are not constantly fighting the compiler over names.
4. Special Keywords — field and it
Kotlin has two special keywords: field and it. They are special because they have very specific roles, but they can also be used as identifiers in some contexts.
field
field is used inside a property's custom getter or setter. It refers to the backing field — the actual storage for the property value. Without field, you cannot access the stored value inside a custom accessor.
class Person {
var name: String = ""
set(value) {
field = value.trim() // "field" refers to the backing storage
}
}
Here, field is necessary. If you wrote name = value inside the setter, it would call the setter again and again — infinite recursion. field breaks the cycle by accessing the raw storage.
it
it is the implicit name of a single parameter in a lambda expression. When you have a lambda that takes exactly one parameter and you do not give it a name, Kotlin calls it it.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { println(it) } // "it" is each number
}
Here, it refers to each element in the list as forEach processes it. You did not have to write { number -> println(number) }. Kotlin gives you it for free.
Both field and it can be used as regular identifiers too, but their special meaning only applies in the right context.
Kotlin Variables: var vs val
Now that we have keywords out of the way, let's talk about variables. Kotlin gives you two ways to declare a variable: var and val. The difference is simple but important.
Mutable variable — var
A var variable can be changed after it is created. It is mutable. You can assign a new value whenever you want.
fun main() {
var name = "deep singh"
println(name) // deep singh
name = "ramesh" // allowed, var is mutable
println(name) // ramesh
}
Think of a var like a whiteboard. You can write on it, erase it, and write something new. The whiteboard itself does not change — only what is written on it.
Immutable variable — val
A val variable cannot be changed after it is assigned. It is immutable. It works like a constant or read-only variable.
fun main() {
val name = "deep singh"
println(name) // deep singh
name = "ramesh" // ERROR: val cannot be reassigned
}
Think of a val like a printed certificate. Once it is printed, you cannot change the name on it. You can read it as many times as you want, but you cannot write over it.
When to use var and when to use val
- Use val by default — it makes your code safer and easier to reason about
- Use var only when you truly need to change the value — like a counter in a loop, or a temporary accumulator
- val does not mean the object inside is immutable — it only means the reference cannot change. A val list can still have elements added to it.
Declaring a variable with an explicit type
Kotlin can usually figure out the type from the value. But you can also write it explicitly:
var name: String = "deep singh" // explicit type
var age: Int = 25 // explicit type
var score = 95.5 // Kotlin infers Double
You can also declare first and initialize later:
var name: String
name = "deep singh" // initialized later
This is useful when the value depends on some condition or calculation that happens after the variable is declared.
Kotlin Data Types — 5 groups you must know
Every variable in Kotlin has a type. The type decides what kind of value it can hold and what operations you can do with it. Kotlin has five main groups of data types:
- Numbers — Byte, Short, Int, Long, Float, Double
- Booleans — true or false
- Characters — single characters like 'a', 'b', 'c'
- Strings — groups of characters like "Hello World"
- Arrays — collections of similar objects
Let's go through each one with examples.
Numbers: Byte, Short, Int, Long, Float, Double
Kotlin gives you six numeric types. They differ in size and what kind of numbers they can hold.
Byte — 1 byte (8 bits)
Range: -128 to 127. Use it when you need to save memory and your values fit in this small range.
fun main() {
var num: Byte = 90
println("$num")
}
Short — 2 bytes (16 bits)
Range: -32768 to 32767.
fun main() {
var num: Short = 90
println("$num")
}
Int — 4 bytes (32 bits)
Range: -2^31 to 2^31. This is the default type for whole numbers in Kotlin. If you write var num = 90, Kotlin makes it an Int.
fun main() {
var num: Int = 90
println("$num")
var num2 = 90 // also Int, inferred
println("$num2")
}
Long — 8 bytes (64 bits)
Range: -2^63 to 2^63. Use it when your number is too big for Int.
fun main() {
var num = 90909070907 // automatically Long because it is too big for Int
println("$num")
var num2 = 90L // L suffix forces Long
println("$num2")
}
Notice: if the digit is more than Int can hold, Kotlin automatically makes it a Long. You can also add the L suffix to be explicit.
Float — 4 bytes (32 bits)
For decimal numbers. Needs an F suffix.
fun main() {
var num = 90.6F
println("$num")
}
Double — 8 bytes (64 bits)
For decimal numbers with more precision. This is the default for decimals in Kotlin. If you write var num = 90.6, it is a Double.
fun main() {
var num = 90.6 // Double by default
println("$num")
}
Number — the parent type
If you want a variable that can hold any numeric type, use Number:
fun main() {
var num: Number = 90.6
println("$num")
}
This is useful when you do not know the exact numeric type in advance.
Boolean, Character, and String
Boolean
A Boolean holds either true or false. Nothing else.
fun main() {
var status = true
if (status) {
println("success")
} else {
println("fail")
}
}
Booleans are the foundation of every if statement, every while loop, and every condition in your program.
Character
A Character holds a single character in single quotes. Like 'a', 'b', 'c'.
fun main() {
var a: Char = 'b'
println("$a")
var b = 't'
println("$b")
}
Characters cannot hold numbers. var b = 12 gives a compile-time error because 12 is an Int, not a Char.
Special characters can be escaped with a backslash: \t (tab), \n (newline), \b (backspace), \r (carriage return).
You can also use Unicode characters like '\u0000'.
String
A String is a group of characters in double quotes. Like "Hello World".
Strings are immutable — once created, they cannot be changed. You can access characters by index.
fun main() {
val values = "Kotlin"
for (s in values) {
println(s)
}
}
Kotlin has two types of string literals:
1. Escaped String
Uses escape sequences like \n for newline.
fun main() {
var s = "Hello \n Kotlin"
println(s)
}
2. Raw String
Uses triple quotes. Can contain newlines and arbitrary text. No escaping needed.
fun main() {
var data = """
Hello Friends
How are you?
"""
println(data)
}
Raw strings are great for multi-line text, SQL queries, JSON, and anything where you want to preserve formatting exactly as written.
Arrays in Kotlin — two ways to create them
An Array is a predefined class that holds similar types of objects. It has get and set functions, a size property, and other useful member functions.
You can create an array in two ways:
a. Using Library Function
arrayOf() creates an array with the values you pass:
fun main() {
var data = arrayOf(1, 11, 22, 33, 44)
for (num in data) {
print("$num ")
}
}
arrayOfNulls() creates an array of a given size with null values:
var data = arrayOfNulls<Int>(5) // array of 5 nulls
b. Using Factory Function
The Array() factory function takes a size and a lambda that returns the initial value for each index:
fun main() {
// Creates: ["0", "2", "4", "6", "8", "10"]
var data = Array(6) { i -> (i + i).toString() }
for (num in data) {
print("$num ")
}
}
Important points about arrays
- You cannot assign an
Array<Int>to anArray<Number>. This way Kotlin reduces possible runtime errors. - You can represent arrays of primitive types without boxing overhead:
ByteArray,IntArray,ShortArray, etc. - These primitive arrays are not inherited from
Arrayclass, but they have the same set of methods and properties.
fun main() {
val data: IntArray = intArrayOf(21, 13, 11)
data[0] = data[1] + data[2]
println(data[0]) // 24
}
Using primitive arrays like IntArray is more memory-efficient than using Array<Int> because there is no boxing and unboxing overhead.
Common questions
What are keywords in Kotlin in simple words?
Keywords are special reserved words that the Kotlin compiler already knows. They have a fixed meaning and cannot be used as normal variable names. Kotlin divides them into hard, soft, modifier, and special keywords.
What is the difference between var and val in Kotlin?
var creates a mutable variable whose value can be changed later. val creates an immutable variable whose value cannot be changed after it is assigned. val works like a constant or read-only variable.
What are the main data types in Kotlin?
Kotlin has five main data type groups: Numbers (Byte, Short, Int, Long, Float, Double), Booleans, Characters, Strings, and Arrays.
What is the difference between Float and Double in Kotlin?
Float uses 4 bytes (32 bits) and needs an F suffix like 90.6F. Double uses 8 bytes (64 bits) and is the default for decimal numbers in Kotlin. Double is more precise than Float.
Can we use soft keywords as variable names in Kotlin?
Yes, soft keywords like by, catch, get, set, and where can be used as identifiers. They only act as keywords in specific contexts, so they are safe to use as variable names.
What is the default type of a decimal number in Kotlin?
In Kotlin, a decimal number like 90.6 is treated as Double by default. If you want a Float, you must add the F suffix, like 90.6F.
Where to go next
You now know the foundation of Kotlin: the four types of keywords, the difference between var and val, and all the main data types with real examples.
If you remember only one thing, remember this: Kotlin is designed to be safe and concise. Use val by default, use var only when you need to change a value, and let the compiler infer types whenever possible.
The next step is to open your IDE and type these examples yourself. Try changing val to var and see what errors you get. Try creating an array and iterating over it. Try using a raw string with triple quotes. That is how the knowledge sticks.
If this helped, bookmark it. The real learning happens when you write the code, break it, and fix it yourself.
No comments:
Post a Comment