Lesson contents

Scala — Data types and type inference

Scala infers a static type for a val when it can determine the type of the initializer. Explicit annotations help distinguish identifiers from calculated amounts.

A simple example

Tell a number from text

  1. Start with 2 and "2"
  2. Do this Add or join
  3. Result 4 and 22
Adding two numbers gives 4. Joining two copies of the text gives the two characters 22.
Lesson.scala
object Lesson extends App {
    println(2 + 2)
    println("2" + "2")
}
Output
4
22
Advertisements

Choosing a data type

Type or declaration Example Use
String "007" Keeps the textual identifier intact.
Int 125 A signed 32-bit integer on the JVM.
Long 125L A signed 64-bit integer. Widen a factor before a large multiplication.
Double 0.25 Represents a floating-point measurement.
Boolean true An if or while condition requires a Boolean expression.

Keep a product identifier and its price distinct

Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. The product code is a String and the quantity and price are Int values. Converting the code to an Int would remove the leading zeros from its displayed form.

Product label: 007. Quantity × price: 3 × 125¢. Line total: 375¢.
Keep a product code intact

A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.

Run the example

Use Scala 2.13. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val product: String = "007"
    val quantity: Int = 3
    val priceCents = 125
    val total = quantity * priceCents
    println(s"$product: $total cents")
  }
}
Output
007: 375 cents

The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.

Try it yourself

Change the code to 010 and the quantity to zero. What should stay visible?

Check your answer

The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.

Scala language specification

Related tags

  • Scala
  • data types
  • text
  • integer values