Scala monads - “value map is not a member of” error

南楼画角 提交于 2019-12-11 18:29:52

问题


I have created a simple trait and service:

@finalAlg
@autoFunctorK(true)
trait BettingService[F[_]] {    
  def put(bet: Bet): F[Bet]
}

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

Bet and BetId are case classes:

case class Bet(betId: BetId, stake: BigDecimal, name: String)

case class BetId(betId: String) extends AnyVal

When I ran this program, I got an error: Error:(12, 21) value map is not a member of model.Bet <- Bet(BetId(id), bet.stake, bet.name) It is something strange for me - why I cannot return good type from for-comprehension? The idea of this is to return same object as given as parameter, but with random id.

I thought that maybe I need instance of new Bet class, but then I could not return it as F[_] as I think.


回答1:


Bet(BetId(id), bet.stake, bet.name) is of type Bet but expected type is F[Bet].

Try

import cats.syntax.functor._

for {
  created <- Applicative[F].pure(Bet(BetId(id), bet.stake, bet.name))
} yield created

or

import cats.syntax.functor._
import cats.syntax.applicative._

for {
  created <- Bet(BetId(id), bet.stake, bet.name).pure
} yield created

or

Applicative[F].pure(Bet(BetId(id), bet.stake, bet.name))

or

import cats.syntax.applicative._

Bet(BetId(id), bet.stake, bet.name).pure


来源:https://stackoverflow.com/questions/55767864/scala-monads-value-map-is-not-a-member-of-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!