Kotlin Data Types Decoded: Your Complete Guide to Numbers, Strings, and More
Defining Variables with Data Types in Kotlin 🧠
In Kotlin, data types classify the kind of values a variable can hold. Here’s the breakdown of the main groups: 🌟
- 🔢 Numbers – For all your numeric needs!
- ✍️ Characters – Single letters or symbols.
- ✅ Booleans – True or false, simple as that!
- 📝 Strings – Sequences of text.
- 📚 Arrays – Collections of values in one variable.
Numbers 🔢
Numbers split into two camps—whole and fractional:
Integer Types (Whole Numbers): Perfect for counting without decimals—positive or negative!
- 💾 Byte: 8 bits, ranges from -128 to 127.
- 📏 Short: 16 bits, spans -32,768 to 32,767.
- 🔍 Int: 32 bits, covers -2,147,483,648 to 2,147,483,647.
- 🌍 Long: 64 bits, a massive -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (add 'L' for clarity).
Floating-Point Types (Decimals): For numbers with fractional parts—think precision!
- 🌊 Float: 32 bits, ranges from 3.4e-38 to 3.4e+38 (use 'F' suffix).
- 💧 Double: 64 bits, spans 1.7e-308 to 1.7e+308—ideal for high precision.
val small: Byte = 100 // Tiny but mighty
val medium: Short = 5000 // Middle ground
val count: Int = 100000 // Everyday use
val big: Long = 15000000000L // Huge numbers
val price: Float = 5.75F // Light decimals
val precise: Double = 5.9999 // Extra precise
Characters ✍️
The Char type holds a single character, wrapped in single quotes—think 'A', '9', or even '😊'!
- 📌 Must use single quotes (not double).
- 🎨 Supports Unicode—emojis included!
val letter: Char = 'K' // Simple char
val emoji: Char = '🌟' // Unicode fun
Booleans ✅
The Boolean type is all about logic—only true or false. Great for decisions!
- 👍 Used in conditions (if/else).
- ⚖️ Just two values, no in-between.
val isReady: Boolean = true // Yes!
val isDone: Boolean = false // Nope!
Strings 📝
The String type stores text—a sequence of characters in double quotes.
- ✂️ Can be concatenated with +.
- 📏 Length accessed via .length.
val greeting: String = "Hello, Kotlin!" // Text magic
Arrays 📚
The Array type bundles multiple values into one variable using arrayOf().
- 📋 Comma-separated values inside.
- 🔢 Access by index (starts at 0).
val colors = arrayOf("Red", "Blue", "Green") // Array of strings
Pro Tips & Notes 🎯
- 🌐 Type Inference: Skip the type—Kotlin guesses Int for whole numbers, Double for decimals.
- 🎲 Float vs. Double: Float offers 6-7 digits of precision; Double gives 15—go Double for accuracy!
- 🚫 No ASCII Tricks: Unlike Java, Kotlin won’t let you use numbers (e.g., 66) as chars—stick to quotes.
- ⚡ Memory Savers: Use Byte or Short when values are small to optimize.
val inferred = 42 // Int by default
val precise = 3.14159 // Double by default
..
Comments
Post a Comment