Overloading General Implicit Conversions

I have a small scala problem (version 2.8.0RC1) with implicit conversions. Whenever more than one implicit conversion is imported, the first becomes shaded. Here is the code where the problem occurs:

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

When uncommenting the second import statement, everything goes wrong, as the first "extendToMonad" is shaded.

However, this works:

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

So where is the catch? What am I missing?

Regards, raichoo

+3
source share
2 answers

In fact, bindings and imported bindings are shaded by name. This applies equally to imported implicit conversions.

, :

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

Scalaz, scalaz.{Functor, Scalaz, MA}, . , typeclass Monad[X] - Monad.

+1

,

implicit object IdentityMonad extends Monad[Value] 

,

implicit object MaybeMonad extends Monad[Maybe]

. , , . , .

0

Source: https://habr.com/ru/post/1742700/


All Articles