在scala中,因?yàn)椴皇羌兒瘮?shù)式,所以一定會(huì)出現(xiàn)帶有副作用的函數(shù),那么有一個(gè)方式可以表示一個(gè)無(wú)參函數(shù)是否有副作用.
無(wú)副作用的無(wú)參函數(shù)調(diào)用時(shí),不加(),有副作用的無(wú)參函數(shù)調(diào)用時(shí)加()
例如:
def withSideEffect() : Unit {
println("我有副作用")
}
def withoutSideEffect() : Unit{
1
}
withSideEffect() //調(diào)用withSideEffect函數(shù)
withoutSideEffect //調(diào)用withoutSideEffect函數(shù)
正如Martin Odersky說(shuō)的
The convention is that you include parentheses if the method has side effects, such as println(), but you can leave them off if the method has no side effects, such as toLowerCase invoked on aString