Scala FlatMap和应用上下文边界产生编译错误

时间:2019-02-23 12:10:03

标签: scala functional-programming scala-cats

我正在Scala做一些工作人员,遇到implicit实例的问题。让我们考虑以下示例:

import cats.{Applicative, FlatMap, Monad}
import cats.syntax.functor._
import cats.syntax.flatMap._
import cats.syntax.applicative._


class Test[F[_]: Monad] extends App{
  val t1 = ().pure[F]
  val t2 = ().pure[F]

  def testFlatApplicative: F[Unit] =
    for{
      _ <- t1
      _ <- t2
    } yield ()
}

这可以编译。但是由于cats.Monad[F[_]]的声明如下:

@typeclass trait Monad[F[_]] extends FlatMap[F] with Applicative[F]

我希望以下内容也能正常工作

import cats.{Applicative, FlatMap, Monad}
import cats.syntax.functor._
import cats.syntax.flatMap._
import cats.syntax.applicative._


class Test[F[_]: FlatMap : Applicative] extends App{
  val t1 = ().pure[F]
  val t2 = ().pure[F]

  def testFlatApplicative: F[Unit] =
    for{
      _ <- t1
      _ <- t2
    } yield ()
}

但是它无法编译并显示错误:

Error:(16, 12) value map is not a member of type parameter F[Unit]
      _ <- t2

这很奇怪。 Apply扩展了Functor ...

任何人都可以解释这种行为吗?

1 个答案:

答案 0 :(得分:5)

class Test[F[_] : FlatMap : Applicative]被减为

class Test[F[_]](implicit flatMap: FlatMap[F], applicative: Applicative[F])

如果您对理解和语法不满意,则会发现问题:

def testFlatApplicative: F[Unit] = 
  FlatMap[F].flatMap(t1)(_ => 
    Functor[F].map(t2)(_ => ())
  )

Error: ambiguous implicit values:
 both value applicative in class Test of type cats.Applicative[F]
 and value flatMap in class Test of type cats.FlatMap[F]
 match expected type cats.Functor[F]

因此您可以手动解决歧义:

def testFlatApplicative: F[Unit] = 
  FlatMap[F].flatMap(t1)(_ => 
    applicative.map(t2)(_ => ())
  )

def testFlatApplicative: F[Unit] = 
  FlatMap[F].flatMap(t1)(_ => 
    flatMap.map(t2)(_ => ())
  )

class Test[F[_]: Monad]时没有这种问题,因为您只有一个隐式。