In Kotlin, variables and data types are fundamental concepts that allow you to store and manipulate data. Here’s an overview of how to declare and use variables along with the common data types in Kotlin:
Variables in Kotlin
Kotlin has two main types of variables: val
and var
.
val
: Declares a read-only variable. Once assigned, its value cannot be changed (similar tofinal
in Java).var
: Declares a mutable variable. Its value can be changed.
Declaring Variables
val readOnly: String = "Hello, World!" // Immutable variable
var mutable: Int = 42 // Mutable variable
Type Inference
Kotlin can automatically infer the type of the variable based on the assigned value, so you can omit the explicit type declaration.
val inferredReadOnly = "Hello, World!" // Type is inferred as String
var inferredMutable = 42 // Type is inferred as Int
Common Data Types in Kotlin
- Numbers
- Int: 32-bit integer
- Long: 64-bit integer
- Short: 16-bit integer
- Byte: 8-bit integer
- Double: 64-bit floating-point number
- Float: 32-bit floating-point number
val myInt: Int = 100
val myLong: Long = 10000000000L
val myShort: Short = 10
val myByte: Byte = 1
val myDouble: Double = 123.45
val myFloat: Float = 123.45F
Characters
- Char: Represents a single character
val myChar: Char = 'A'
Boolean
- Boolean: Represents a true/false value
val myBoolean: Boolean = true
Strings
- String: Represents a sequence of characters
val myString: String = "Kotlin"
Examples of Using Variables and Data Types
Here are some examples demonstrating variable declaration and initialization with different data types:
fun main() {
// Immutable variables (val)
val name: String = "Alice"
val age: Int = 25
val pi: Double = 3.14159
val isStudent: Boolean = true
val grade: Char = 'A'
// Mutable variables (var)
var count: Int = 0
count += 1 // count is now 1
// Type inference
val city = "New York" // Kotlin infers the type as String
var temperature = 30.5 // Kotlin infers the type as Double
// Printing values
println("Name: $name")
println("Age: $age")
println("Pi: $pi")
println("Is Student: $isStudent")
println("Grade: $grade")
println("Count: $count")
println("City: $city")
println("Temperature: $temperature")
}
Summary
val
: Immutable variable.var
: Mutable variable.- Kotlin supports various data types such as
Int
,Long
,Short
,Byte
,Double
,Float
,Char
,Boolean
, andString
. - Type inference allows you to omit explicit type declarations.
Understanding these basics will help you get started with Kotlin and write more complex programs efficiently.