Basic Data Types and Variables in Kotlin
Let's get started.
Kotlin is a modern, concise and safe programming language that runs on the JVM and is fully interoperable with Java. One of the first steps in learning Kotlin is understanding how it deals with data types and variables.
In this article, we are going to explore how Kotlin handles variables and the different kinds of data types. Also we will see how Kotlin’s type system helps prevent common programming errors.
Lets start with Variables in Kotlin
Variables are used to store data in your Kotlin program. Kotlin defines two types of variables:val name = "Kotlin"
println(name)
//Lets try to assign another value to above definition and we will have error
name = "Java" // Error: Val cannot be reassigned
This is similar to declaring a constant in other programming languages. Immutable variables make your code more predictable and easier to debug.
var age = 25
println(age)
//Since this is a Mutable variable we can reassign without an issue
age = 26 // Works fine
println(age)
In Kotlin, it’s a best practice to use val whenever possible, and only use var when mutation is required.
Let's take a look at Type Inference in Kotlin
Kotlin can often infer the type of a variable from its initial value, so specifying the type explicitly is optional.
val country = "Turkey" // Compiler infers String type
var score = 95 // Compiler infers Int type
// You can also declare types explicitly for clarity:
val country1: String = "Turkey"
var score1: Int = 95
Let's take a look at Basic Data Types in Kotlin
Kotlin’s data types are similar to those in Java but implemented as objects rather than primitive types. The compiler automatically optimizes them to primitive types at runtime when possible.
| Data Type | Size | Short Description |
|---|---|---|
| Byte | 8 | Small integer value |
| Short | 16 | Short integer |
| Int | 32 | Standard integer |
| Long | 64 | Large integer |
| Float | 32 | Floating-point number |
| Double | 64 | Double-precision float |
| Char | 16 | Single character |
| Boolean | 1 | True/false value |
| String | Various | Sequence of characters |
val b: Byte = 100
val s: Short = 10000
val i: Int = 100000
val l: Long = 1000000000L
val f: Float = 10.5F
val d: Double = 20.99
val grade: Char = 'A'
val isActive: Boolean = true
val message: String = "Hello"
Lets also check casting Numbers and Type Conversion
Kotlin does not automatically convert between numeric types. You must explicitly convert using conversion functions such as .toInt(), .toDouble(), .toFloat(), etc. This reduces potential data loss bugs that can happen due to implicit type conversions.
Below you can see the example of number type conversionval number: Int = 100
val longNumber: Long = number.toLong() // Explicit conversion
println(longNumber)
Let's also see Strings in Kotlin
Strings in Kotlin are immutable sequences of characters. You can declare them using double quotes ("...") and perform various operations easily. Kotlin also supports string templates, which let you embed variables or expressions directly inside strings
val language = "Kotlin"
println(language.length) // Prints 6
println(language.uppercase()) // Prints KOTLIN
// String Templates example
val name = "Alex"
val score = 98
println("Hi $name! Your score is $score.")
// You can also use expressions inside {...}:
println("Next year, your score will be ${score + 2}.")
Discover the Null Safety feature of Kotlin
Kotlin’s type system is designed to eliminate the NullPointerException (NPE) which is most famous error type of Java. By default, all types are non-nullable in Kotlin. If you really want a variable to hold a null value, declare it as nullable by adding a ? after the type. For accessing the value of a nullable variable, use the safe call operator (?.)
var text: String = "Hello"
text = null // Not Allowed. Compile-time error
// Nullable variable definition
var ntext: String? = "Hello"
ntext = null // Allowed
// Accessing value of nullable variable
println(text?.length) // Prints "null" if text is null
// Use the Elvis operator (?:) to provide a default value:
println(text?.length ?: 0) // Prints 0 if text is null
Finally let's check the Constants in Kotlin
If a value is known at compile time and won’t change, you can use the const modifier with val. This makes the variable a compile-time constant, similar to static final in Java.
const val API_VERSION = "1.0"
Let's Wrap Up the article
Kotlin’s variable system and data types are designed with safety, clarity, and conciseness in mind. With immutable variables (val), strong typing, and null safety features, Kotlin helps prevent many of the run-time bugs that plague older languages.That is all.
Burak Hamdi TUFAN