I have the following code:
val text = "some text goes here"
val (first, rest) = text.splitAt(4)
println(first + " *" + rest)
That works fine.
However, I want to have two cases, defining "first" and "rest" outside, like this:
val text = "some text goes here"
var (first, rest) = ("", "")
if (text.contains("z")) {
(first, rest) = text.splitAt(4)
} else {
(first, rest) = text.splitAt(7)
}
println(first + " *" + rest)
But that gives me an error:
scala> | <console>:2: error: ';' expected but '=' found.
(first, rest) = text.splitAt(4)
Why is it an error to do (first, rest) = text.splitAt(4) but not to do val (first, rest) = text.splitAt(4)? And what can I do?
Edit: Can't re-assign val, changed to var. Same error
In Scala, reassignment to val is not allowed, but we can create a new val and assign the value to it. We can see an error when reassigning the values to a val . As a workaround, we can assign the result to a new val and use it.
Printing Variables In the code snippet above, we simply passed the name of our variable to the print statement and in return, the value assigned to the variable, i.e. 5, was displayed.
In Scala there are two types of variables: Mutable Variables. Immutable Variables.
The answer by Serj gives a better way of writing this, but for an answer to your question about why your second version doesn't work, you can go to the Scala specification, which makes a distinction between variable definitions and assignments.
From "4.2 Variable Declarations and Definitions":
Variable definitions can alternatively have a pattern (§8.1) as left-hand side. A variable definition
var p = e
wherep
is a pattern other than a simple name or a name followed by a colon and a type is expanded in the same way (§4.1) as a value definitionval p = e
, except that the free names inp
are introduced as mutable variables, not values.
From "6.15 Assignments":
The interpretation of an assignment to a simple variable
x = e
depends on the definition ofx
. Ifx
denotes a mutable variable, then the assignment changes the current value ofx
to be the result of evaluating the expressione
.
(first, rest)
here is a pattern, not a simple variable, so it works in the variable definition but not in the assignment.
First of all val
is immutable, so you can't reassign it. Second, if
, like all control structures in Scala, can return a value. So, you can do it like this:
val text = "some text goes here"
val (first, rest) = if (text.contains("z")) text.splitAt(4) else text.splitAt(7)
println(first + " *" + rest)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With