Data Types in Kotlin
In Kotlin, data types are used to define the type of data that a variable can hold. Kotlin is a statically typed language, which means the type of a variable is known at compile time. Here are the basic data types in Kotlin:
1. **Numbers**
Kotlin provides several types to represent numbers, which are divided into integer and floating-point types.
Integer Types:
- **Byte**: 8-bit signed integer. Range: -128 to 127.
- **Short**: 16-bit signed integer. Range: -32,768 to 32,767.
- **Int**: 32-bit signed integer. Range: -2^31 to 2^31-1.
- **Long**: 64-bit signed integer. Range: -2^63 to 2^63-1.
#### Floating-Point Types:
- **Float**: 32-bit floating-point number.
- **Double**: 64-bit floating-point number.
2. **Booleans**
- **Boolean**: Represents a true or false value.
3. **Characters**
- **Char**: Represents a single 16-bit Unicode character.
4. **Strings**
- **String**: Represents a sequence of characters. Strings in Kotlin are immutable.
5. **Arrays**
- **Array**: Represents an array of elements. Kotlin provides specialized classes for arrays of primitive types, such as `IntArray`, `ByteArray`, `CharArray`, etc.
6. **Nullable Types**
- Kotlin has built-in support for nullable types, which allows a variable to hold either a value or `null`. For example, `Int?` can hold an integer or `null`.
7. **Any**
- **Any**: The root of the Kotlin class hierarchy. Every Kotlin class has `Any` as a superclass. It is equivalent to `Object` in Java.
8. **Unit**
- **Unit**: Represents a type with only one value, `Unit`. It is similar to `void` in Java, but it is a proper type.
9. **Nothing**
- **Nothing**: Represents a value that never exists. It is used as the return type for functions that never return (e.g., functions that always throw an exception).
### Example Usage:
```kotlin
fun main() {
// Numbers
val byteValue: Byte = 127
val intValue: Int = 2147483647
val longValue: Long = 9223372036854775807L
val floatValue: Float = 3.14f
val doubleValue: Double = 3.141592653589793
// Boolean
val isKotlinFun: Boolean = true
// Character
val grade: Char = 'A'
// String
val message: String = "Hello, Kotlin!"
// Array
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
// Nullable type
val nullableInt: Int? = null
// Any
val anyValue: Any = 42
// Unit
fun printMessage(): Unit {
println("This is a message.")
}
// Nothing
fun throwException(): Nothing {
throw IllegalArgumentException("This function never returns normally.")
}
}
```
Type Inference:
Kotlin supports type inference, which means you don't always have to explicitly specify the type of a variable. The compiler can often infer the type from the context:
```kotlin
val inferredInt = 42 // Type inferred as Int
val inferredDouble = 3.14 // Type inferred as Double
Kotlin's type system is designed to be concise and safe, with features like nullable types and type inference helping to reduce boilerplate code and prevent common errors.
Comments
Post a Comment