Luong Ba Linh
Luong Ba Linh

Reputation: 802

Why print() has side effects?

Why does print() method in Scala have side effects? All it does is to read, not to write. In other words, print() does not mutate anything.

I seems to be a "stupid" question, but sometimes the little things lead to big moves.

Upvotes: 3

Views: 2135

Answers (3)

Ingo
Ingo

Reputation: 36339

The output of the program could be connected to a rocket launcher, who understands, among others, the following command:

LAUNCH ROCKETS 1,7,13

Now, would you say that printing LAUNCH ROCKETS 1,7,13 has no side effect? What if I told you that rocket 13 is targeted at your house?

Upvotes: 1

Not to have side effects for a function means that a call to it can be replaced by its return value. print does not return any value so if it was pure (it had no side effects) it could be replaced by NOT-OPERATION.

However, as you can see in your terminal, when you call print something happens: Some text gets printed in the screen. That is not NOT-OPERATION and therefore, print has side effects.

Upvotes: 12

Odomontois
Odomontois

Reputation: 16308

As @lyjackal perfectly said print() mutates System.out.

For example this two definitions

def sumA = {
  val x = foo
  val y = bar
  val z = baz
  x + y + z
}


def sumB = {
  val x = foo
  val z = baz
  val y = bar
  x + y + z
}

should be the same if both foo and bar have no side effects

So lines

println(s"By the way your result is $sumA")

and

println(s"By the way your result is $sumB")

should define identical behaviour from techical and user perspective

but consider this definitions of those functions

def foo = {
  println("Good to see you sir!")
  1
}

def bar = {
  println("I hate you")
  2
}

def baz = {
  println("Just joking")
  3
}

could now those behaviours seen as equivalent from user perspective?

Upvotes: 3

Related Questions