Developus
Developus

Reputation: 1462

Scala, cats - how to do not use Applicative[F] explicity?

I would like to use Applicative[F] in some other way then explicity. Currently I have a simple code:

class BettingServiceMock[F[_] : Async] extends BettingService[F] {    
      override def put(bet: Bet): F[Bet] = {
        for {
          created <- Bet(Some(BetId(randomUUID().toString)), bet.stake, bet.name).pure
        } yield created
      }
    }

Bet is just a simple case class. I use method pure explicity to return F[Bet]. Is there some way to do not it like this way (to do not call pure method explicity)? I tried to do something like this:

class BettingServiceMock[F[_] : Async] (implicit a:Applicative[F]) extends BettingService[F] {

  override def put(bet: Bet): F[Bet] = {
    for {
      created <- Bet(Some(BetId(randomUUID().toString)), bet.stake, bet.name)
    } yield created
  }
}

It did not help, because I got an error: value map is not a member of model.Bet <- (Some(BetId(randomUUID().toString)), bet.stake, bet.name)

I would like to discover some good practise in Cats that's way I'm asking about it. I do not thnik so that explicity call methids like pure is good practise. Could you help me with that?

Upvotes: 1

Views: 401

Answers (1)

Some Name
Some Name

Reputation: 9540

First of all, why do you think it's a bad practice. That's a common Applicative syntax. If you want some "magic" automatically lifts your value Bet to Applicative[Bet] then you would need sort of implicit conversion and that would be really bad practice.

You take a look at the scaladoc example of Applicative https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/Applicative.scala

Applicative[Option].pure(10)

Here the Applicative[Option] instance was summoned by apply[F[_]](implicit instance: Applicative[F]) which is automatically generated by simulacrum's @typeclass.

Upvotes: 4

Related Questions