-
Notifications
You must be signed in to change notification settings - Fork 1
HowTo Import
So all the examples of Scalaz either tell you to just import the kitchen sink
import scalaz._
import Scalaz._or don't provide any guidance at all!
Working with specific Scalaz imports isn't hard once you figure it out. Basically apply these rules.
- Start by thinking of the
scalaz.syntax(orscalaz.syntax.std) helpers you're going to need and what data types (fromscalazor more oftenscalaz.std) you will be working with. - If you are using some specific Scalaz data structure or typeclass you'll need to import it from
scalazto work with it.
Keep in mind that Scalaz tends to make a distinction between Scalaz types and Scala types. As such you'll find things in scalaz.syntax for Scalaz syntaxes and things in scalaz.syntax.std for syntaxes on Scala things.
Working with an IDE like IntelliJ can be really helpful here. You can pull in the kitchen sink, get your code working, and then remove the kitchen sink and start adding in explicit imports until you figure out the right ones you need. It gets easier with practice!
import scalaz.std.anyVal._
import scalaz.syntax.id._
def addOne(x: Int): Int = x + 1
def queryThing(query: Symbol): Int = 4
queryThing('myDatabaseInfo) |> addOneHere I wanted |>. We need to import the syntax and the type we are working on. (scalaz.std.anyVal covers basic stuff like Byte, Int, Double. It's a common mistake [at least I keep making it] to forget that String isn't a basic type.)
import scalaz.syntax.std.option._
4.some // Option[Int] = Some(4)You might then be surprised that none[Boolean] doesn't work. That's because you are now after a constructor and not after syntax. As such
import scalaz.std.option._
none[Boolean] // Option[Boolean] = NoneSuppose I have a Map[Int,Set[String] being unique words of the given length. Maybe we're in a distributed system and have gotten such things many times over and now we want to aggregate them all. Luckily we can sum these things up because Maps form Monoids if the values are Monoids.
So what are we going to need here. We want |+| syntax. We're going to need to trick out Scala's Maps and Sets. We don't need std.anyVal because the keys don't matter and in this case we won't need std.string because a Semigroup on a collection doesn't need to know about the content type.
import scalaz.std.map._
import scalaz.std.set._
import scalaz.syntax.semigroup._
Map(4 -> Set("safe")) |+| Map(4 -> Set("lock")) // Map(4 -> Set("safe", "lock"))