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

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

作者: xor_eax_eax | 来源:发表于2018-03-02 10:04 被阅读0次

    在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

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/yqwoxftx.html