本文介绍了Scala monads-“价值图不是"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

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.

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

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

推荐答案

Bet(BetId(id), bet.stake, bet.name)类型为Bet,但预期类型为F[Bet].

Bet(BetId(id), bet.stake, bet.name) is of type Bet but expected type is 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

这篇关于Scala monads-“价值图不是"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 13:28