Kamil Banaszczyk
Kamil Banaszczyk

Reputation: 1153

Scalaz validation NEL mkString

i'm trying to learn scalaz validation, and given this piece of code:

          AuthorValidator.validate(author) match {
            case scalaz.Success(authorValidated) => onSuccess(authorService.addAuthor(authorValidated)) { extract: Int =>
                complete(StatusCodes.OK -> extract+"")
              }
            case scalaz.Failure(failure) => complete(StatusCodes.Accepted, failure mkString "/") // this piece won't work
          }
        }

I want to obtain formatted string from failure : NonEmptyList[String]. Basically, i can't use mkString. Do you know if scalaz provide some way to format NEL ?

Upvotes: 2

Views: 581

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

A NonEmptyList is just a list with one extra guarantee (non-emptiness), so you can always safely convert one to an ordinary Scala List in order to use methods like mkString:

import scalaz.NonEmptyList, scalaz.syntax.foldable._

def formatNel(nel: NonEmptyList[String]): String = nel.toList.mkString("/")

The foldable syntax import provides the toList method via the Foldable instance for NonEmptyList. You could also use nel.list.toList to convert first to a scalaz.IList, but that's a little more verbose and may be less efficient for large lists (off the top of my head I'm not sure).

There are also lots of other ways you could write this directly, without converting to a Scala list. One would be to convert to an IList and then use intersperse and suml:

import scalaz.NonEmptyList, scalaz.std.string._, scalaz.syntax.foldable._

def formatNel(nel: NonEmptyList[String]): String = nel.list.intersperse("/").suml

For something like formatting as a string, though, I'd probably stick to toList.mkString, since it's clear, familiar, and may be more efficient since it's less generic than suml (although that's unlikely to matter much in most cases).

Upvotes: 2

Related Questions