未返回或分配的值会怎样?

What happens with values that are not returned or assigned?

我遇到了一个函数:

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

函数中的第一条和最后一条语句不执行任何操作。我知道什么是Class.forNamereturns,但是返回值并没有在任何地方使用,也没有赋值。 true 也一样。只是代码中间的一个true

你能给我解释一下 Scala 的这个特性吗?

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

语句位置的纯表达式将不执行任何操作并被丢弃:

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

关于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.

请注意,尽管 Class.forName 没有被分配给任何东西,但这并不意味着它什么都不做,它被认为是 open 的 side-effect 在范围外改变程序的状态共 open.