Kotlin Data Types: Your Guide to Storing Values Like a Pro! ð§
In Kotlin, data types define what kind of values a variable can hold, making your code safe and expressive. ð Whether you’re counting numbers, crafting text, or building collections, Kotlin’s got you covered! Let’s dive into every data type with beginner-friendly flair and pro-level depth! ð
- ðĒ Numbers: Whole or decimal, for all your math needs! ð
- ✍️ Characters: Single letters, symbols, or emojis. ðĻ
- ✅ Booleans: True or false for logical decisions. ⚖️
- ð Strings: Text sequences for messages and more. ✉️
- ð Arrays & Collections: Group multiple values in style! ð️
Numbers ðĒ
Numbers come in two flavors: integers (whole) and floating-point (decimals). Kotlin offers a range of types for precision and memory efficiency! ð
Integer Types (Whole Numbers): Ideal for counts, IDs, or indices—positive or negative! ð§Ū
- ðū Byte: 8 bits, -128 to 127. Perfect for tiny values! ð
- ð Short: 16 bits, -32,768 to 32,767. Middle ground! ⚖️
- ð Int: 32 bits, -2,147,483,648 to 2,147,483,647. Your go-to! ð
- ð Long: 64 bits, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Massive! ð (Use L suffix.)
Floating-Point Types (Decimals): For fractions, measurements, or scientific calculations! ð§
- ð Float: 32 bits, 6-7 digits precision, 1.4e-45 to 3.4e+38. (Use F suffix.) ðŠķ
- ð§ Double: 64 bits, 15-16 digits precision, 4.9e-324 to 1.7e+308. High accuracy! ðŊ
val tiny: Byte = 100 // ð Tiny number
val medium: Short = 5000 // ⚖️ Medium range
val count: Int = 100000 // ð Everyday integer
val huge: Long = 15000000000L // ð Big number
val price: Float = 5.75F // ðŠķ Light decimal
val precise: Double = 5.9999 // ðŊ High precision
fun main() {
println(tiny) // Outputs: 100 ð
println(count) // Outputs: 100000 ð
println(precise) // Outputs: 5.9999 ð
}
Pro Tip: Use Int and Double for most cases; reserve Byte or Short for memory-critical apps! ðū
Characters ✍️
The Char type holds a single Unicode character in single quotes—letters, digits, or emojis! ð
- ð Requires single quotes ('A', not "A"). ✏️
- ðĻ Supports Unicode, including emojis like ð or ð. ð
val letter: Char = 'K' // ✍️ Simple character
val digit: Char = '9' // ðĒ Numeric character
val emoji: Char = 'ð' // ð Unicode emoji (Use String for emoji)
fun main() {
println(letter) // Outputs: K ð
}
Watch Out: Unlike Java, Kotlin doesn’t allow numbers (e.g., 65) as Char values—use quotes! ðŦ
Booleans ✅
Boolean is for logic: just true or false. Perfect for conditions and flags! ⚖️
- ð Drives if, while, and other control flows. ð ️
- ⚖️ Only two values—no gray areas! ðĶ
val isActive: Boolean = true // ✅ Ready to go
val isComplete: Boolean = false // ðŦ Not done
fun main() {
println(isActive) // Outputs: true ð
println(isComplete) // Outputs: false ð
}
Fun Fact: Booleans are lightweight, using just 1 bit internally! ðŠķ
Strings ð
String stores text sequences in double quotes, from names to messages. ✉️
- ✂️ Concatenate with + or use string templates with $. ð§ĩ
- ð Check length with .length or manipulate with methods like uppercase(). ð§
val greeting: String = "Hello, Kotlin!" // ✉️ Text sequence
val name: String = "Alice" // ð User name
fun main() {
println(greeting) // Outputs: Hello, Kotlin! ð
println("$name rocks!") // Outputs: Alice rocks! ð
println(name.length) // Outputs: 5 ð
}
String Tip: Use raw strings (""") for multi-line text or JSON! ð
Arrays ð
Array groups multiple values of the same type, created with arrayOf(). ð️
- ð Values are comma-separated. ð
- ðĒ Access via index (0-based). ð
val colors = arrayOf("Red", "Blue", "Green") // ð Array of strings
val numbers = arrayOf(1, 2, 3, 4) // ðĒ Array of integers
fun main() {
println(colors[0]) // Outputs: Red ð
println(numbers[2]) // Outputs: 3 ð
}
Array Tip: Use size to get length and avoid index-out-of-bounds errors! ⚠️
Collections: Lists, Sets, Maps ð️
Beyond arrays, Kotlin’s collections (List, Set, Map) offer flexible ways to store multiple values! ðĶ
- ð List: Ordered, allows duplicates. Use listOf(). ð
- ð§đ Set: Unordered, no duplicates. Use setOf(). ðŦ
- ðš️ Map: Key-value pairs. Use mapOf(). ð
val fruits = listOf("Apple", "Banana", "Apple") // ð Ordered, duplicates OK
val unique = setOf("Red", "Blue", "Red") // ð§đ No duplicates
val scores = mapOf("Alice" to 95, "Bob" to 88) // ð Key-value pairs
fun main() {
println(fruits[1]) // Outputs: Banana ð
println(unique) // Outputs: [Red, Blue] ð
println(scores["Alice"]) // Outputs: 95 ð
}
Collection Tip: Use mutable versions (mutableListOf(), etc.) for dynamic updates! ð
Nullable Types ðĻ
Kotlin’s null safety prevents crashes by distinguishing nullable (?) and non-null types. ðĄ️
- ð Non-null by default; add ? for nullable types. ð
- ð ️ Use safe calls (?.) or Elvis operator (?:) for null handling. ð§
val name: String? = null // ð Nullable string
val city: String = "Paris" // ð Non-null
fun main() {
println(name?.length ?: 0) // Outputs: 0 ð
println(city.length) // Outputs: 5 ð
}
Null Safety Tip: Always handle null cases to avoid runtime errors! ⚠️
Unsigned Integer Types ðĒ
Unsigned types (e.g., UInt, ULong) store only non-negative integers, doubling the positive range! ð
- ð UInt: 0 to 4,294,967,295. Use u suffix. ð
- ð ULong: 0 to 18,446,744,073,709,551,615. Use uL suffix. ð
val unsignedCount: UInt = 100u // ð Positive only
val bigUnsigned: ULong = 5000uL // ð Large positive
fun main() {
println(unsignedCount) // Outputs: 100 ð
println(bigUnsigned) // Outputs: 5000 ð
}
Unsigned Tip: Use for sizes, counts, or IDs where negatives aren’t needed! ✅
Type Casting and Checking ð
Convert or check types safely with toX(), as, or is operators! ð§
- ð is: Checks if a variable is a specific type. ðĩ️♂️
- ð ️ as?: Safe cast to avoid crashes. ðĄ️
val input: String = "123" // ð String
val number: Int = input.toInt() // ðĒ Convert to Int
fun main() {
println(number) // Outputs: 123 ð
val anyValue: Any = "Hello"
if (anyValue is String) {
println(anyValue.length) // Outputs: 5 ð
}
}
Casting Tip: Use as? for safe casts to handle type mismatches gracefully! ð§
Pro Tips & Best Practices ðŊ
- ð Type Inference: Let Kotlin guess types (val x = 42 → Int) for cleaner code. ðŠķ
- ðē Float vs. Double: Choose Double for precision; Float for memory savings. ðŊ
- ⚡ Memory Optimization: Use Byte or Short for small values in performance-critical apps. ðū
- ðĄ️ Null Safety: Prefer non-null types; use nullable only when necessary. ðĻ
- ð Collections over Arrays: Use List or Set for flexibility unless arrays are required. ð️
- ðĒ Unsigned Types: Opt for UInt or ULong for positive-only values like sizes. ð
val inferred = 42 // ðĒ Int inferred
val precise = 3.14159 // ð§ Double inferred
val safe: String? = null // ð Nullable string
fun main() {
println(inferred) // Outputs: 42 ð
println(precise) // Outputs: 3.14159 ð
println(safe) // Outputs: null ð
}
Frequently Asked Questions (FAQ) ❓
- What’s the difference between Int and Long? ðĪ
Int is 32-bit (-2.1B to 2.1B); Long is 64-bit (-9 quintillion to 9 quintillion). Use Long for large numbers. ð - When to use Float vs. Double? ðē
Double (64-bit) offers higher precision; Float (32-bit) saves memory but is less accurate. Prefer Double for most cases. ð§ - Can I use numbers as Char values? ðŦ
No, Kotlin requires single quotes for Char (e.g., 'A'), not numbers like in Java. ✍️ - How does null safety work with data types? ðĻ
Add ? for nullable types (e.g., String?); non-null types prevent null errors by default. ðĄ️ - What’s the difference between Array and List? ð
Array has fixed size; List is more flexible and supports dynamic operations. Use List for most cases. ð️ - Are unsigned types common? ðĒ
UInt and ULong are niche but useful for positive-only values like sizes or IDs. ð
..
Tags:
Kotlin