Scala monads-“值映射不属于”错误

时间:2019-04-19 21:06:27

标签: scala monads scala-cats

我创建了一个简单的trait和服务:

@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
  }
}

BetBetIdcase classes

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

case class BetId(betId: String) extends AnyVal

运行该程序时,出现错误:Error:(12, 21) value map is not a member of model.Bet <- Bet(BetId(id), bet.stake, bet.name)对我来说很奇怪-为什么我不能从for-comprehension返回好的类型?这样的想法是返回与给定参数相同的对象,但是具有随机ID。

我以为也许我需要新的Bet类的实例,但是后来我无法像我想的那样将其返回为F[_]

1 个答案:

答案 0 :(得分:3)

reconnectInterval的类型为Bet(BetId(id), bet.stake, bet.name),但预期类型为Bet

尝试

F[Bet]

import cats.syntax.functor._

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

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

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

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