Can mutable Collection.empty methods break Scala's null-argument naming convention?

This is how the method is .empty

declared in the object scala.collection.mutable.Map

in Scala 11.5:

def empty[A, B]: Map[A, B]

      

Should this method have empty parentheses, for example?

def empty[A, B](): Map[A, B]

      

The Scala page suggests naming conventions without explicitly saying that omitting parentheses in the 0-arity method is a convention for purely functional code, and including empty parentheses means that the method has a side effect. (I think I ran into an error message more explicit about this.)

A volatile method .empty

has a side effect in that you can distinguish the results of individual calls from .empty

. Shouldn't it have empty parentheses, even though its helper immutable.Map

doesn't work?

Regarding my own code, is there a special naming convention that I have to follow when creating and returning a mutable object from a 0-arity method?

+3


source to share


2 answers


Not. scala.collection.mutable.Map.empty[A, B]

has no side effects. It is a method that returns a new mutable.Map[A, B]

one every time you call it.

mutable.Map#empty

(the method of the trait itself) also returns a new empty of mutable.Map

the same type. It is not empty collection (as it seems it can), so there are no side effects.



See source if you are unsure.

+6


source


This is all a bit of a mess on the JVM.

With operations such as eq / ne and System.identityHashCode, even creating a new immutable object has observable side effects (namely, increasing some counter deep in the JVM, the next object will have a different reference hash code). So, in JVM country, a function that does nothing but return a new object is considered side-effect-free as you might get. If the returned object is modified, the referential transparency still exits the window, even if the function that produces the mutable object itself is considered to be free of side effects.



If you are really pedantic, the JVM has no free functions that return non-primitives.

scala> import scala.collection.immutable._
scala> SortedSet.empty[Int] eq SortedSet.empty[Int]
res4: Boolean = false

      

+1


source







All Articles