开发者

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开发者_如何学Python 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?


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.


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.


there is only the immutable List. There is only one instance of an EmptyList, therefore a class level empty doesn't make sense.

The Map trait can be implemented by mutables, therefore you need multiple instances.

... I think there is something missing with this explanation, but maybe it is a start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜