Free excerpt from TypeSafe (pdf): Scala for the Impatient
I discovered the special syntax for a field setter:
class Person {
private var privateAge = 0 // Make private and rename
def age = privateAge
def age_ = (newValue: Int) {
if (newValue > privateAge) privateAge = newValue; // Can’t get younger
}
}
Error:
<console>:10: error: not found: value newValue
def age_ = (newValue: Int) {
It needed to be age_=
(no space between the age_
and the =
). I didn't realize that <identifier>_=
is a special syntax. I'm used to =
being a token for assignment.
object Accounts {
private var lastNumber = 0
def newUniqueNumber = { lastNumber += 1; lastNumber}
}
// > defined module Accounts
class Accounts private(val id: Int, initialBalance: Double) {
private var balance = initialBalance
}
// > defined class Accounts
But got this error:
warning: previously defined object Accounts is not a companion to class Accounts.
Companions must be defined together; you may wish to use :paste mode for this.
Don't bother using :paste
if you are in the IntelliJ Scala console, as I was. You exit paste-mode with Ctrl-d, but IntelliJ captures that keystroke, so your only option is to quit the console process.
def doWhat(color: TrafficLightColor.Value) {
if (color == TrafficLightColor.Red) "Stop"
else if (color == TrafficLightColor.Green) "Go"
else if (color == TrafficLightColor.Yellow) "Slow Down!"
else throw new IllegalArgumentException("error")
}
Error:
<console>:7: error: not found: value TrafficLightColor
def doWhat(color: TrafficLightColor.Value) {
^
<console>:8: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
if (color == TrafficLightColor.Red) "Stop"
^
<console>:9: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
else if (color == TrafficLightColor.Green) "Go"
^
<console>:10: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
else if (color == TrafficLightColor.Yellow) "Slow Down!"
The error misled me into thinking I was doing the if/else block wrong (btw, I am aware that pattern matching is more idiomatic). In fact, the problem was that def
requires an =
, i.e. def doWhat(color: TrafficLightColor.Value) = { ...
Googling for warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
did not yield any useful results, so if you found this page searching for the meaning of that error, I hope this helped you.
It did, thanks!