0

I'm learning to use Scala cats library. Quite often I see this type of definition like

implicit def validatedApplicative[E : Semigroup]: Applicative[Validated[E, ?]] = ???
def parallelValidate[E : Semigroup, A, B, C](v1: Validated[E, A], v2: Validated[E, B])(f: (A, B) => C): Validated[E, C] = ???
def parse[A : Read](key: String): Validated[ConfigError, A] = ???
  • Can someone tell me why we are defining the A is of type ClassName in generics for [A : ClassName]?

  • What additional benefit we get when we write a method definition as

    def parse[A : Read](key: String): Validated[ConfigError, A]

    instead of

    def parse(key: String): Validated[ConfigError, Read]

    for a method declaration?

Puneeth Reddy V
  • 1,538
  • 13
  • 28
  • 3
    I think you have a wrong perception of what [T: Type] syntax is. It's a context bound. def foo[A: Read](a: A) is equivalent to def foo[A](a: A)(implicit ev: Read[A]). It means "this is some A for which an implicit instance of Read[A] exists somewhere in scope" – slouc Sep 11 '18 at 14:44
  • Thank you, for clarifying this doubt. – Puneeth Reddy V Sep 11 '18 at 14:52

1 Answers1

0

Cats uses type classes everywhere, that's something you should look into it when you want to learn more of the functional approach.

Type classes can be defined like:

trait Read[A] {
  def read(in: A): String
}

when specifying a type like this: [A : Read]

you are requesting that the type used A must have in scope an implementation of the typeClass Read.

This makes writing generic code quite simple compare of requiring your type to extend many different interfaces...

I believe in cats website there are some blogs introducing to type classes

FerranJr
  • 332
  • 1
  • 8