Jas
Jas

Reputation: 15113

is a call to create a new object instance considered pure or not?

in functional programming terminology if I perform:

val a = new Client
val b = new Client

Is calling the above constructor twice considered a pure or a non pure function?

Upvotes: 1

Views: 92

Answers (2)

paradigmatic
paradigmatic

Reputation: 40461

If you can substitute your two lines by:

val a = new Client
val b = a

without changing the whole program behavior, the object instantiation could be considered as pure (referential transparency).

It will fail if the Client constructor has any "observable" side effect, or if you use identity equality in the program.

Upvotes: 6

Ganesh Sittampalam
Ganesh Sittampalam

Reputation: 29110

Generally memory allocation is not considered to be a side-effect and so a constructor call in itself is considered to be pure.

Although it could eventually cause your program to run out of memory, this isn't something you can really control as a programmer, so "purity" is generally considered on the assumption of infinite memory.

If your constructor itself has a side-effect, then calling it would not be pure.

Upvotes: 4

Related Questions