I have the following method where I am searching for the position of a character in a 2D vector.
def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
var pos: Pos
pos.x = levelVector.indexWhere(row => row.indexOf(c) > 0)
pos.y = levelVector(pos.x).indexOf(c)
pos
}
pos
has two integer fields which remember positions on the x and y axis
However, on the line var pos: Pos
I am getting the error Block cannot contain declarations
.
Why can't the block contain declarations? Which is the issue with my code?
your problem is that you are writing
var pos:Pos
you should write instead :
val pos = new Pos(...)
Anyway , while reading your code its kind of java written in scala. if you can be immutable, so be. in scala you should instantiante your class with the variables. which means you cannot change the state of the class i.e statements like
pos.x = //something
pos.y = //something
is changing the state of the variable pos. I would reccomend to be immutable i.e
val x = //something
val y = //something
val newPos = Pos(x,y)
Have fun
Complementing the selected answer, the problem with
var pos: Pos
is that pos
was not initialized with anything (thus the "declaration" error).
These two initializations would be valid (for a general case):
var pos: Pos = null
// or
var pos: Pos = new Pos(...)
But in your case, you should use val
followed by the constructor
val newPos = new Pos(...)
As mentioned, use immutability in Scala whenever is possible.
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