问题描述
我创建了一个简单的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
}
}
Bet
和BetId
是case 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-“价值图不是"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!