- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 337字
- 2021-07-23 16:25:13
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.
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
- 網(wǎng)管員典藏書架:網(wǎng)絡管理與運維實戰(zhàn)寶典
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- HTML5 Game development with ImpactJS
- 正在爆發(fā)的互聯(lián)網(wǎng)革命
- Yii Application Development Cookbook(Second Edition)
- Learning Swift(Second Edition)
- Spring 5.0 Projects
- CCNP TSHOOT(642-832)認證考試指南
- 網(wǎng)絡環(huán)境中基于用戶視角的信息質量評價研究
- Learning Storm
- Practical Web Penetration Testing
- Hands-On Microservices with Node.js
- 中國互聯(lián)網(wǎng)發(fā)展報告2021
- 物聯(lián)網(wǎng)基礎及應用
- 網(wǎng)絡基本通信約束下的系統(tǒng)性能極限分析與設計