我遇到了一个函数:
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的这一功能吗?
答案 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 }}。