Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test on empty value universal for all types

Tags:

scala

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.

like image 760
Nikita Volkov Avatar asked Dec 29 '11 22:12

Nikita Volkov


2 Answers

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.

like image 175
missingfaktor Avatar answered Sep 25 '22 13:09

missingfaktor


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
}
like image 30
Destin Avatar answered Sep 26 '22 13:09

Destin