[SOLVED] Check passed in arguments in functional way


#1

Usually I do null, empty data check for arguments passed in. For example,

case class MyClass(a: String = "", b: String = "") {
    require(null != a && !"".equals(a))
    ...
}

But I am interested in more functional style. Normally how is this done with more functional way?

What I can think of is

case class MyClass(a: Option[String] = None, b: Option[String] = None) {
    for {
        aa <- a
        bb <- b
    } yield (aa, bb)
}

But the above code would create None if one of arguments are None, which might not be the result I expect because sometimes I want to keep arguments data as is if they still contain data while others are None.

case class MyClass(a: Option[String] = None, b: Option[String] = None) {
    a.flatMap { e => b.flatMap { e1 => ... }; ... }
}

Though I also uses the code similar to the one above, I suppose there would have a better way than nested checking.

I understand those are not a good way to do that, so I appreciate any suggestions.

Thanks


#2

The really functional way of validation is exemplified by scalaz validation. See http://eed3si9n.com/learning-scalaz/Validation.html for a good introduction.

The Play Framework uses a similar mechanism for JSON validation.

Brian Maso


#3

Thanks for the answer.