官术网_书友最值得收藏!

Side effects

A function or expression is said to have a side effect when it modifies some state or has some action in the outside world. For instance, printing a string to the console, writing to a file, and modifying a var, are all side effects.

In Scala, all expressions have a type. A statement which performs a side effect is of type Unit. The only value provided by the type Unit is ():

scala> val x = println("hello")
hello
x: Unit = ()

scala> def printName(name: String): Unit = println(name)
printName: (name: String)Unit

scala> val y = {
var a = 1
a = a+1
}
y: Unit = ()

scala> val z = ()
z: Unit = ()

A pure function is a function whose result depends only on its arguments, and that does not have any observable side effect. Scala allows you to mix side-effecting code with pure code, but it is a good practice to push side-effecting code to the boundaries of your application. We will talk about this later in more detail in the Ensuring referential transparency section in Chapter 3, Handling Errors.

Good practice: When a function with no parameters has side effects, you should declare it and call it with empty brackets (). It informs users of your function that it has side effects. Conversely, a pure function with no parameters should not have empty brackets, and should not be called with empty brackets. IntelliJ helps you in keeping some consistency: it will display a warning if you call a parameterless function with (), or if you omit the () when you call a function declared with  ().

Here is an example of a method call with a side effect where we have to use empty brackets, and an example of a pure function:

scala> def helloWorld(): Unit = println("Hello world")
helloWorld: ()Unit

scala> helloWorld()
Hello world

scala> def helloWorldPure: String = "Hello world"
helloWorldPure: String

scala> val x = helloWorldPure
x: String = Hello world
主站蜘蛛池模板: 广德县| 四子王旗| 东山县| 三都| 扎囊县| 北京市| 新兴县| 尚志市| 三门县| 吉水县| 赤城县| 平潭县| 黄大仙区| 乡宁县| 衡水市| 尼木县| 牙克石市| 离岛区| 泸水县| 乌鲁木齐市| 伊吾县| 正镶白旗| 泰来县| 天等县| 崇州市| 莱阳市| 连平县| 资中县| 沙河市| 永靖县| 济宁市| 三穗县| 佛山市| 万源市| 翁源县| 嘉黎县| 邢台市| 上饶市| 平阳县| 建瓯市| 门头沟区|