Empty test is universal for all types

I am looking for a test solution if the value of any type is empty (or the default). That is, some method on Any that checks if the instance String "" , a Int - to 0 , a Float - to 0f , a Boolean - to false , a List does not contain elements, etc. for other types. Primarilly I wonder if there is any solution in the standard library, and if not how you implement it. I believe this may be useful, and if it does not exist in the standard library, this should be suggested.

+6
source share
2 answers

Use the 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 on a topic.

+11
source

Instead of passing objects of type T, you can transfer things of type Option [T], wrapping all valid things of type T, for example

 val thing = 1 val thingOption = Some(thing) 

and saving all invalid data like Nones for example

 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 } 
+2
source

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


All Articles