Managing imports in Scalaz7

2019-01-25 07:46发布

I am using scalaz7 in a project and sometimes I run into issues with imports. The simplest way get started is

import scalaz._
import Scalaz._

but sometimes this can lead to conflicts. What I have been doing until now the following slightly painful process:

  • work out a minimal example that needs the same imports as my actual code
  • copy that example in a separate project
  • compile it with the option -Xprint:typer to find out how the code looks after implicit resolution
  • import the needed implicits in the original project.

Although this works, I would like to streamline it. I see that scalaz7 has much more fine-grained imports, but I do not fully understand how they are organized. For instance, I see one can do

import scalaz.std.option._
import scalaz.std.AllInstances._
import scalaz.std.AllFunctions._
import scalaz.syntax.monad._
import scalaz.syntax.all._
import scalaz.syntax.std.boolean._
import scalaz.syntax.std.all._

and so on.

How are these sub-imports organized?

As an example, say I want to work with validations. What would I need, for instance to inject validation implicits and make the following compile?

3.fail[String]

What about making ValidationNEL[A, B] an instance of Applicative?

1条回答
Rolldiameter
2楼-- · 2019-01-25 08:24

This blog post explains the package structure and imports a la carte in scalaz7 in detail: http://eed3si9n.com/learning-scalaz-day13

For your specific examples, for 3.failure[String] you'd need:

import scalaz.syntax.validation._

Validation already has a method ap:

scala> "hello".successNel[Int] ap ((s: String) => "x"+s).successNel[Int]
res1: scalaz.Validation[scalaz.NonEmptyList[Int],java.lang.String] = Success(xhello)

To get the <*> operator, you need this import:

import scalaz.syntax.applicative._

Then you can do:

"hello".successNel[Int] <*> ((s: String) => "x"+s).successNel[Int]
查看更多
登录 后发表回答