In your description, you ask how
filter out all elements of the array that contain only an empty string.
The currently accepted answer does this, but also filters out empty arrays and arrays containing several empty strings (i.e. not only [""]
, but also []
and ["", "", ""]
, etc. d.). (In fact, the first part x.isEmpty ||
completely redundant.) If you translate your requirement literally, if your array is xss
, you need
xss.filter(_ != Array(""))
This does not work, because the equals
method for Java arrays does not work, as you might expect . Instead, when comparing arrays, use the sameElements
or deep
:
xss.filterNot(_ sameElements Seq("")) xss.filter(_.deep != Seq(""))
In idomatic Scala code, you do not use Array
much, so this does not happen too often. Prefer Vector
or List
.
source share