Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some collection classes have an "empty" instance method additionally to the class method?

Both exist for example here:

Map.empty[Int, Int]
Map(1 -> 41).empty

Set().empty
Set.empty

But here only the class methods are existing:

List.empty        //OK
List(1,2,3).empty //Doesn't exist

Array.empty       //OK
Array("a").empty  //Doesn't exist

Isn't empty a perfect case for a class method (and shouldn't the instance method empty be deprecated therefore)?

Or should the an empty instance method be added to classes missing it?

Is there anything from a language point of view which makes it difficult only having empty as a class method (e. g. type inference, higher-kinded types, ...).

PS: It was suggested that Maps with default values would be harder to achieve without an instance method empty:

Map[Int, Int](1->2, 21->42).withDefault(_*2).empty

What do you think?

like image 843
soc Avatar asked Mar 19 '26 22:03

soc


2 Answers

That's true, empty could be a method on the class instance. A reason why it's required by sets and maps is because they implement their builders using this method. I guess a reason why it wasn't included elsewhere is because it wasn't a typical use case.

like image 82
axel22 Avatar answered Mar 22 '26 13:03

axel22


I wonder why does Map have empty, not the other way around. After all, it isn't an operation you do to something, it is just an instance of something.

Anyway:

(List(1, 2, 3): Traversable[Int]).companion.empty

I put in Traversable there just to show this works for any collection.

like image 21
Daniel C. Sobral Avatar answered Mar 22 '26 15:03

Daniel C. Sobral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!