Kotlin Variables Unveiled: Understanding var, val, and Naming Best Practices
In 2025, Kotlin remains a standout language for its sleek, intuitive variable handling. Whether you’re a newbie or a pro, variables are your gateway to Kotlin’s magic. Let’s explore every angle of Kotlin variables with flair! π
- ✨ Create variables effortlessly with var or val, assigning values using the equal sign (=).
- π var variables are flexible and can be updated anytime, while val locks in a value for good—no changes allowed! π
- π§ Kotlin’s type inference skips the need for explicit types, making your code cleaner and faster to write.
Type Magic: No Guesswork Needed! πͺ
Kotlin doesn’t demand you declare types like "String" or "Int"—it’s smart enough to detect them automatically:
var name = "John" // String (text)
val birthyear = 1992 // Int (number)
var price = 19.99 // Double (decimal)
From "John" as a String to 19.99 as a Double, Kotlin’s got it covered without extra typing! π
..
Delayed Assignment? Specify the Type! ⏳
You can declare a variable now and assign it later, but you’ll need to tell Kotlin the type upfront:
var name: String
name = "John"
println(name) // Outputs: John
var age: Int = 25 // Optional: assign at declaration
Pro Tip: Uninitialized var variables must be assigned before use, or Kotlin will throw an error! ⚠️
..
When to Use val? Lock It In! π
val is your best friend for constants—values that stay put, like PI or app settings:
val PI = 3.14159 // Forever 3.14159
val appVersion = "1.0.0" // No updates here!
Attempting to reassign a val? Kotlin says, “Nope!”—perfect for safety. π«
- π Short or Sweet Names: Use x or y for quick tasks, or userAge, totalSum, maxVolume for clarity.
- π‘ Allowed Characters: Letters, digits, underscores (_), and dollar signs ($) are fair game.
- π¦ Start Right: Begin with a letter—numbers or symbols won’t fly.
- π‘ Special Starts: $ or _ are okay (e.g., $price), but we’ll skip them in this guide.
- π Case Sensitivity: myVar and myvar are different—watch those capitals!
- π Lowercase Start: Begin with lowercase (e.g., firstName), and no whitespace allowed.
- π« No Reserved Words: Keywords like var, val, or String are off-limits as names.
- πͺ CamelCase FTW: Combine words with capitals (e.g., myFavoriteColor, calculateTotalScore).
- π Scope Matters: Variables live where you declare them—inside a function (local) or outside (global).
- ⏲️ Late Initialization: Use lateinit var for non-null variables you’ll assign later (but only for var, not val!).
- π’ Common Types: Beyond String and Int, try Double, Float, Boolean (true/false), and more.
- ⚡ Reassignment Rules: Change a var anytime, but its type stays fixed (e.g., no turning an Int into a String).
val globalLimit = 100 // Accessible everywhere
fun testScope() {
var localCount = 5 // Only lives here
}
Comments
Post a Comment