4

I've encounter a function:

def open(partitionId: Long,version: Long): Boolean = {
    Class.forName("com.mysql.jdbc.Driver")
    connection = DriverManager.getConnection(url, user, pwd)
    statement = connection.createStatement
    true
  }

The first and the last statements in the function don't do anything. I know what Class.forName returns, but the returned value is not used anywhere and there is no assignment. Same thing for true. Just a true in the middle of the code.

Could you please explain to me this feature of Scala?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Alon
  • 10,381
  • 23
  • 88
  • 152
  • 2
    [If there is no return then the last expression is taken to be the return value.](https://stackoverflow.com/a/12560532/5205022) – Mario Galic Jun 15 '19 at 17:23
  • @MarioGalic and what about the first statement in the function? – Alon Jun 15 '19 at 17:24
  • 1
    [A Driver class is loaded, and therefore automatically registered with the DriverManager by calling the method Class.forName](https://stackoverflow.com/a/2093100/5205022) – Mario Galic Jun 15 '19 at 17:29
  • @MarioGalic OK thanks. You can write it as an answer and I will accept it. – Alon Jun 15 '19 at 17:36

1 Answers1

5

If there is no return then the last expression is taken to be the return value.

Pure expressions in statement position would do nothing and be discarded:

def foo = {
  val x = 1
  "hello" // discarded
  x       // returned as result of foo
}

Regarding side-effect

Class.forName("com.mysql.jdbc.Driver")

this seems to have been a way of loading the JDBC driver which is now deprecated:

Applications no longer need to explicitly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

Note despite Class.forName not being assigned to anything it does not mean it is doing nothing, it is considered a side-effect of open mutating the state of the program outside the scope of open.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98