简体   繁体   中英

global, default implicits in scalaz (scalaz7)

When I code using Scalaz I often encounter problems, that there is no implicit in scope. I think there should be some default implicits somwhere in vast package scalaz, but either I don't know where or there are not any.

Suppose we want to show any Any in scalaz (I am using scalaz 7):

scala>     import scalaz._
import scalaz._

scala>     import Scalaz._
import Scalaz._

scala>     {def a: Any = "sratatata"; a}.show
<console>:14: error: could not find implicit value for parameter F0: scalaz.Show[Any]
{def a: Any = "sratatata"; a}.show
^

That is not working becouse there is no implicit Show[Any] in scope.

Why Scalaz doesn't provide it? Is the good approach to use some global Show[A] ? I mean something like this:

scala> implicit def anyShow[A] = Show.showFromToString[A]
anyShow: [A]=> scalaz.Show[A]

scala> {def a: Any = "sratatata"; a}.show
res0: scalaz.Cord = sratatata

I think the same touches Equal .

EDIT

I've tried as mentioned in answers to add import scalaz.syntax.ShowSyntax but that doesn't resolve my problem. See:

scala>     import scalaz._
import scalaz._

scala>     import Scalaz._
import Scalaz._

scala>     import scalaz.syntax._
import scalaz.syntax._

scala>     import scalaz.syntax.ToShowOps
import scalaz.syntax.ToShowOps

scala>     import scalaz.syntax.ShowSyntax
import scalaz.syntax.ShowSyntax

scala>     {def a: Any = "sratatata"; a}.show
<console>:19: error: could not find implicit value for parameter F0: scalaz.Show[Any]
{def a: Any = "sratatata"; a}.show

Compiler still wants some implicit scalaz.Show[Any] .

Show is only useful if you statically know the types; if you only know that you have an Any , just call a.toString.

If you want Show[String] , import scalaz.std.string._ ; for Show[List[String]] you would need to import both scalaz.std.list._ and scalaz.std.string._ .

Alternatively, you can import all the provided type class instances for the standard library with scalaz.std.AllInstances._ .

This is explained step-by-step during @eed3si9n's excellent Learning Scalaz series.

There are also some good guides for Scalaz here:

Good scalaz introduction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM