I'm looking for a solution for testing if a value of any type is empty (or default). I.e. some kind of method on Any
that tests if a String
instance is equal to ""
, an Int
- to 0
, a Float
- to 0f
, a Boolean
- to false
, a List
contains no items and so on for other types. Primarilly I'm interested whether some solution already exists in the standard library and if not how you would implement it. I believe this could be useful and if it doesn't exist in the standard library it should be suggested.
Use Zero
type-class from Scalaz.
scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._
scala> def isEmpty[A : Zero](value: A) = value == mzero[A]
isEmpty: [A](value: A)(implicit evidence$1: scalaz.Zero[A])Boolean
scala> isEmpty("")
res0: Boolean = true
scala> isEmpty(List())
res1: Boolean = true
scala> isEmpty(false)
res2: Boolean = true
scala> isEmpty("O HAI")
res3: Boolean = false
Link to a blog post of mine on a related topic.
Instead of passing around things of type T, you could pass around things of type Option[T], wrapping all valid things of type T, like so
val thing = 1
val thingOption = Some(thing)
and storing all invalid data as Nones, like so
val thingOption = None
Then, if you want to make a decision based on the value of thingOption, you can do it like this
thingOption match {
case None => // Whatever you want to do with defaults
case Some(x) => // Whatever you want to do with 'thing' if it isn't a default
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With