我在使用隐式转换时遇到了一些scala(版本2.8.0RC1)问题。每当导入多个隐式转换时,第一个隐式转换就会被遮盖。这是出现问题的代码:

// containers
class Maybe[T]
case class Nothing[T]() extends Maybe[T]
case class Just[T](value: T) extends Maybe[T]

case class Value[T](value: T)

trait Monad[C[_]] {
  def >>=[A, B](a: C[A], f: A => C[B]): C[B]
  def pure[A](a: A): C[A]
}

// implicit converter
trait Extender[C[_]] {
  class Wrapper[A](c: C[A]) {
    def >>=[B](f: A => C[B])(implicit m: Monad[C]): C[B] = {
      m >>= (c, f)
    }

    def >>[B](b: C[B])(implicit m: Monad[C]): C[B] = {
      m >>= (c, { (x: A) => b } )
    }
  }

  implicit def extendToMonad[A](c: C[A]) = new Wrapper[A](c)
}

// instance maybe
object maybemonad extends Extender[Maybe] {
  implicit object MaybeMonad extends Monad[Maybe] {
    override def >>=[A, B](a: Maybe[A], f: A => Maybe[B]): Maybe[B] = {
      a match {
        case Just(x) => f(x)
        case Nothing() => Nothing()
      }
    }

    override def pure[A](a: A): Maybe[A] = Just(a)
  }
}

// instance value
object identitymonad extends Extender[Value] {
  implicit object IdentityMonad extends Monad[Value] {
    override def >>=[A, B](a: Value[A], f: A => Value[B]): Value[B] = {
      a match {
        case Value(x) => f(x)
      }
    }

    override def pure[A](a: A): Value[A] = Value(a)
  }
}

import maybemonad._
//import identitymonad._

object Main {
  def main(args: Array[String]): Unit = {
    println(Just(1) >>= { (x: Int) => MaybeMonad.pure(x) })
  }
}

当取消注释第二个import语句时,一切都会出错,因为第一个“extendToMonad”被遮盖了。

但是,此方法有效:
object Main {
  implicit def foo(a: Int) = new  {
    def foobar(): Unit = {
      println("Foobar")
    }
  }

  implicit def foo(a: String) = new  {
    def foobar(): Unit = {
      println(a)
    }
  }

  def main(args: Array[String]): Unit = {
    1 foobar()
    "bla" foobar()
  }
}

那么,渔获量在哪里?我想念什么?

问候,
雷乔

最佳答案

实际上,绑定和导入的绑定已被名称遮盖。这同样适用于导入的隐式转换。

我相信您可以在导入过程中重命名作为解决方法:

import IdentityMonad.{extendToMonad => extendToMonadIdentity}
import MaybeMonad.{extendToMonad => extendToMonadMaybe}

您可能想看看Scalaz,尤其是scalaz.{Functor, Scalaz, MA},这是编码这些类型类的另一种方法。特别是在搜索类型类Monad[X]时,将搜索伴随对象Monad

关于scala - 重载通用隐式转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2709541/

10-11 21:23