一个很好的方式表示(无参)函数是否有副作用

2018-03-02  本文已影响0人  xor_eax_eax

在scala中,因为不是纯函数式,所以一定会出现带有副作用的函数,那么有一个方式可以表示一个无参函数是否有副作用.

无副作用的无参函数调用时,不加(),有副作用的无参函数调用时加()

例如:

def withSideEffect() : Unit {
    println("我有副作用")
}

def withoutSideEffect() : Unit{
    1
}

withSideEffect() //调用withSideEffect函数
withoutSideEffect //调用withoutSideEffect函数

正如Martin Odersky说的
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

上一篇下一篇

猜你喜欢

热点阅读