Sure! Data types in Kotlin define the type of data that a variable can hold. Here are some of the basic data types in Kotlin explained with examples:
Int
)Integers represent whole numbers without any decimal points.
Example
val age: Int = 25
val population = 1000000 // Kotlin infers the type as Int
Double
and Float
)Floating-point numbers represent numbers with decimal points.
Example
val pi: Double = 3.14
val gravity: Float = 9.8f // Explicitly specifying type as Float
Char
)Characters represent single characters enclosed within single quotes.
Example
val letter: Char = 'A'
val symbol = '#' // Kotlin infers the type as Char
Boolean
)Booleans represent true or false values.
Example
val isRaining: Boolean = true
val hasPassed: Boolean = false
String
)Strings represent sequences of characters enclosed within double quotes.
Example
val message: String = "Hello, Kotlin!"
val greeting = "Welcome" // Kotlin infers the type as String
Arrays represent collections of elements of the same data type.
Example
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
val colors = arrayOf("Red", "Green", "Blue") // Kotlin infers the type as Array<String>
Kotlin distinguishes between nullable and non-nullable types. Nullable types can hold null values, while non-nullable types cannot.
Example
val nullableString: String? = null
val nonNullableString: String = "Hello"
Understanding data types is crucial for writing correct and efficient Kotlin code. By choosing the appropriate data type for your variables, you can ensure that your program behaves as expected and uses memory efficiently.