Variables, Types and String Templates

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

val vs var

val site = "groovygrails.in"  // read-only, prefer always
var visits = 0               // mutable when truly needed
visits += 1

Type Inference

The compiler infers types, but they are still static: val n = 42 is an Int forever. Declare explicitly at API boundaries: fun total(): Int.

Number and Other Types

  • Int, Long, Double, Float - no primitives vs wrappers split in code.
  • Boolean, Char, String - familiar semantics.
  • Arrays, Ranges - 1..10 and arrayOf(1, 2, 3).

String Templates

val lang = "Kotlin"
println("I love $lang")              // simple name
println("Next year: ${2026 + 1}")    // any expression

Multiline Strings

val json = """
  { "site": "groovygrails.in" }
""".trimIndent()

Key Points

  • Default to val; var only with a reason.
  • Templates replace string concatenation and formatters.
  • Types are inferred but never dynamic.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in