Scala monads - “值映射不是”错误的成员

问题描述 投票:0回答:1

我创建了一个简单的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[_]返回。

scala monads scala-cats
1个回答
3
投票

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))

要么

import cats.syntax.applicative._

Bet(BetId(id), bet.stake, bet.name).pure
© www.soinside.com 2019 - 2024. All rights reserved.