Pattern matches empty ArrayBuffer

Is there any special case class for representing empty ArrayBufferthat can be used when matching patterns similar Nilto lists?

And why does it work:

scala> collection.mutable.ArrayBuffer.empty == Nil
res11: Boolean = true

So far this is not the case:

scala> collection.mutable.ArrayBuffer() match { case Nil => 1 }
<console>:8: error: pattern type is incompatible with expected type;
 found   : scala.collection.immutable.Nil.type
 required: scala.collection.mutable.ArrayBuffer[Nothing]

UPDATE

After some thought, I suppose there is no such class of case. Although existence Nilis vital to work List, arrays do not require a special structure of this kind.

I found a workaround for checking for empty matches, which can work in most cases:

collection.mutable.ArrayBuffer(2) match { 
  case collection.mutable.ArrayBuffer(v, _*) => v * 2
  case _ => 0 
}

First check if the array has at least one element, and otherwise it must be empty. Also, as it turned out, I could just use ArrayBuffer.isEmptyinstead of matching the pattern.

+4
3

Jasper-M ( == , ).

, ArrayBuffer Nil. , List scala (ADT), ArrayBuffer - .

ArrayBuffer. , List : a case object Nil case class ::.

case - , List. ArrayBuffer , .

+5
scala> collection.mutable.ArrayBuffer.empty == Nil
res11: Boolean = true

, equals:

true, , , , false

:

scala> val buffer = collection.mutable.ArrayBuffer.empty[Int]
buffer: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> buffer.append(4)

scala> buffer == List(4)
res1: Boolean = true

, .

+1

, . Nil List, .

, :

collection.mutable.ArrayBuffer(2) match { 
  case collection.mutable.ArrayBuffer(v, _*) => v * 2
  case _ => 0 
}

, , .

0

Source: https://habr.com/ru/post/1544777/


All Articles