Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - block can not contain declarations

Tags:

scala

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?

like image 703
octavian Avatar asked Dec 13 '15 16:12

octavian


2 Answers

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

like image 160
David H Avatar answered Nov 10 '22 19:11

David H


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.

like image 43
Jan K. S. Avatar answered Nov 10 '22 17:11

Jan K. S.