没有返回或分配的值会怎样?

时间:2019-06-15 17:17:34

标签: scala return-value side-effects

我遇到了一个函数:

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

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

您能告诉我Scala的这一功能吗?

1 个答案:

答案 0 :(得分:5)

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
}

关于副作用

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

this似乎是一种加载JDBC驱动程序的方式,该驱动程序现在为deprecated

  

应用程序不再需要使用以下命令显式加载JDBC驱动程序   Class.forName()。当前加载JDBC驱动程序的现有程序   使用Class.forName()可以继续工作而无需修改。

请注意,尽管没有将Class.forName分配给任何事物,这并不意味着它没有执行任何操作,但这被认为是open的副作用,它使程序状态超出{{1 }}。