Imports
The easiest approach to Сats imports is to import everything that's commonly needed:
import cats._
import cats.data._
import cats.syntax.all._
The cats._ import brings in quite a few type classes (similar to interfaces) such as Monad, Semigroup, and Foldable. Instead of the entire cats package, you can import only the types that you need, for example:
import cats.Monad
import cats.Semigroup
import cats.Foldable
The cats.data._, import brings in data structures such as Validated and State. Instead of the entire cats.data package, you can import only the types that you need, for example:
import cats.data.Validated
import cats.data.State
The cats.syntax.all._ import adds syntax enrichment onto certain types to provide some handy methods such as right-biased Either combinators:
import cats.syntax.all._
// Сats adds right-biased combinators to the standard library's Either
val e: Either[String, Int] = Right(3)
// e: Either[String, Int] = Right(value = 3)
e.map(_ + 1)
// res4: Either[String, Int] = Right(value = 4)
// cats adds an orEmpty method to the standard library's Option
val o: Option[String] = None
// o: Option[String] = None
o.orEmpty
// res5: String = ""
If you'd like to import à la carte, you can do so, by importing from cats.syntax for syntax enrichment.
For example, if you'd like to import the Semigroup syntax:
import cats.syntax.semigroup._
"Hello, " |+| "World!"
// res7: String = "Hello, World!"
The import adds the |+| syntax.
Note: Beware that if you import a type class instance or its syntax twice, you will receive conflicting implicits with a less than helpful error message.
This usually happens when importing different type classes in the same hierarchy or when importing syntax enrichment for all type classes using cats.syntax.all._ or cats.implicits._ together with a more specific import like cats.syntax.option._ or cats.instances.either._.
Below is an example of this phenomenon:
import cats.syntax.all._
1 |+| 2
import cats.syntax.semigroup._
3 |+| 5 // error: value |+| is not a member of Int
Compilation fails on the second invocation of |+| because we now have conflicting implicits from Semigroup.