Kotlin Data Types Explained: Numbers, Strings, Booleans, and More for Beginners
- ๐ข 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 ๐ข
- ๐พ 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.)
- ๐ 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 ✍️
- ๐ 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 ✅
- ๐ 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 ๐
- ✂️ 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 ๐
- ๐ 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 ๐️
- ๐ 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 ๐จ
- ๐ 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 ๐ข
- ๐ 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 ๐
- ๐ 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. ๐
Comments
Post a Comment