Why use scala.collection.immutable.Stack

2020-07-03 07:11发布

问题:

I need something to store a LIFO. No need for traversing and other functions except for push and pop.

I've found special class in scala collection for creating a stack. But it lacks Nil object in pattern matching and other handy scala idioms. Immutable lists suit well at first glance, they have cons for construction and for extraction and that is all needed from LIFO.

Is there any reason behind scala.collection.immutable.Stack existence? Why I should prefer to use it, what are use cases to show its benefits?

回答1:

From the API documentation:

Note: This class exists only for historical reason and as an analogue of mutable stacks. Instead of an immutable stack you can just use a list.

And in a little more detail:

Immutable stacks are used rarely in Scala programs because their functionality is subsumed by lists: A push on an immutable stack is the same as a :: on a list and a pop on a stack is the same as a tail on a list.

So to answer your questions:

  1. Yes, there's a reason for its existence.
  2. No, you shouldn't prefer it over lists.


标签: scala