Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Language Basics

Operators and Strings

Learn Scala operators as methods, precedence, equality with ==, and strings: s, f and raw interpolators, multiline strings, common String methods and StringBuilder.

In Scala, an operator is just a method with a symbol for a name. 1 + 2 is really 1.+(2). That idea explains operator precedence, why you can define your own operators, and why strings and collections feel so uniform. In this lesson you will use arithmetic, comparison and logical operators, then move on to the string toolbox: interpolation, multiline literals and the most useful methods.

Operators are methods

SCALA
val sum = 1 + 2         // same as 1.+(2)
val text = "a" + "b"    // same as "a".+("b")
val big = 10.max(3)     // method call with dot
val big2 = 10 max 3     // infix notation: same call

Any method with one parameter can be written in infix form (a method b). Scala 3 asks you to mark methods intended for infix use with the infix modifier when they are alphanumeric, and warns otherwise in strict mode. Symbolic operators are always allowed.

Arithmetic

SCALA
val a = 17
a + 5      // 22
a - 5      // 12
a * 2      // 34
a / 5      // 3   (integer division)
a % 5      // 2   (remainder)
a / 5.0    // 3.4

There are no ++ or -- operators. Use n += 1 and n -= 1 on a var.

SCALA
var counter = 0
counter += 1
counter *= 10   // 10

Division by zero: with Int it throws ArithmeticException; with Double it yields Infinity. The runnable Kotlin demo shows the same JVM rules:

Kotlin Division rules on the JVM (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Comparison and logical operators

SCALA
3 == 3        // true
3 != 4        // true
2 < 5         // true
"a" == "a"    // true: == compares contents (calls equals)
true && false // false (short-circuit)
true || false // true
!true         // false

Unlike Java, Scala's == is safe for objects. It calls equals and handles null for you. Use eq only when you truly want reference identity.

Bitwise operators

SCALA
6 & 3     // 2  (AND)
6 | 3     // 7  (OR)
6 ^ 3     // 5  (XOR)
~6        // -7 (NOT)
1 << 4    // 16 (shift left)
-16 >> 2  // -4 (arithmetic shift right)

Precedence

Precedence is decided by the operator's first character, from lowest to highest:

  1. letters (like max)
  2. |
  3. ^
  4. &
  5. = !
  6. < >
  7. :
  8. + -
  9. * / %
  10. all other symbols

So 2 + 3 * 4 is 14. When in doubt, add parentheses. One more rule: operators ending in : are right-associative, which is how 1 :: List(2, 3) works (it calls :: on the list on the right).

Strings and interpolation

An interpolated string starts with a letter before the opening quote.

SCALA
val name = "Ada"
val age = 36

s"Hello, $name"                 // Hello, Ada
s"Next year: ${age + 1}"        // Next year: 37
s"Upper: ${name.toUpperCase}"   // Upper: ADA

$name inserts a variable; ${...} inserts any expression. For a literal dollar sign, write $$.

The f interpolator adds printf-style formatting and checks the types at compile time:

SCALA
val price = 4.5
f"Price: $price%.2f"      // Price: 4.50
f"$age%05d"               // 00036
f"$name%-6s|"             // Ada   |

The raw interpolator leaves backslashes alone, which suits regex and Windows paths:

SCALA
raw"C:\new\table"         // C:\new\table (no tab or newline)

Multiline strings

Triple quotes create a multiline literal with no escapes. Use .stripMargin to trim the leading |:

SCALA
val poem =
  """Roses are red,
    |Violets are blue.""".stripMargin

poem is two lines with no indentation. Triple quotes also combine with interpolation: s"""Name: $name""".

Common String methods

SCALA
val s = "  Scala is fun  "
s.trim                    // "Scala is fun"
s.length                  // 16
s.trim.split(" ")         // Array("Scala", "is", "fun")
s.contains("is")          // true
s.trim.startsWith("Sc")   // true
s.replace("fun", "great") // "  Scala is great  "
s.trim.toLowerCase        // "scala is fun"
"a,b,c".split(",").toList // List(a, b, c)
"ha" * 3                  // "hahaha"
"scala".capitalize        // "Scala"
"abc".reverse             // "cba"
List("x", "y").mkString(", ") // "x, y"

Some of these (capitalize, *, reverse, take, drop, filter) come from StringOps, a Scala wrapper that makes a String behave like a sequence of characters. That is why "hello".filter(_ != 'l') gives "heo".

Here is the equivalent word-handling in Java, runnable:

Java Common string work (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Comparing and building strings

SCALA
"apple" < "banana"        // true, lexicographic
"Apple".equalsIgnoreCase("apple") // true

For many appends in a loop, avoid repeated + on a var string. Use StringBuilder:

SCALA
val sb = StringBuilder()
for i <- 1 to 3 do sb.append(i).append(",")
sb.toString        // "1,2,3,"

Or build with mkString: (1 to 3).mkString(",") gives "1,2,3".

Characters

Char values use single quotes and behave like small numbers:

SCALA
'a'.toInt        // 97
('a' + 1).toChar // 'b'
'7'.isDigit      // true
'x'.toUpper      // 'X'

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is 1 + 2 in method form?

    Operators are methods, so 1 + 2 is the call 1.+(2).
  2. 2. What does f"$price%.2f" do when price is 4.5?

    The f interpolator applies printf-style formatting, so %.2f shows two decimals.
  3. 3. Which operator compares string contents in Scala?

    == calls equals and is null-safe. eq compares references.
  4. 4. Which interpolator leaves backslashes untouched?

    raw"..." does not process escape sequences.

Summary

  • Operators are methods; infix a op b is the same as a.op(b).
  • Precedence follows the first character of the operator; use parentheses to be clear.
  • == compares values; there is no ++, use += 1.
  • s, f and raw interpolators and triple-quoted strings make text easy to build.
  • StringOps gives strings sequence-like methods such as take, reverse and filter.

Next: Control Flow as Expressions