Skip to content
val, var, and Type Inference
step 1/6

Reading — step 1 of 6

Learn

~1 min readFirst Steps

Two binding keywords:

  • valimmutable binding (like final in Java, const in JS). Idiomatic Scala uses val everywhere possible.
  • var — mutable. Avoid unless you really need mutation.
val name = "Ada"        // type inferred as String
val age: Int = 36       // explicit type annotation
var counter = 0         // mutable
counter += 1

Scala is statically typed but with strong inference. You almost never need to write types except on function parameters.

Common types:

  • Int, Long, Short, Byte — integers
  • Double, Float — floats
  • Boolean — true/false
  • Char, String — text
  • Unit — like void (no meaningful value)
  • Any — top type (everything is an Any)

Read a line: scala.io.StdIn.readLine(). Parse: "42".toInt, "3.14".toDouble.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…