I'm defining a trait which has an abstract type B which I want to use as a monad. To specify that B must be able to act as a monad, I declare an implicit monadB
:
trait A {
type B[_]
implicit def monadB: Monad[B]
}
Then, when I implement this type, I assign a concrete type to B
, such as List
. I then need to provide a concrete definition for the implicit monadB
. It is needed, for example, when calling the method .point[B]
in the function randomDouble
below. How can I do it?
trait A2 extends A {
type B[_] = List[_]
implicit def monadB: Monad[B] = ???
def randomDouble: B[Double] = new Random.nextDouble.point[B]
}
I've tried:
implicit def monadB: Monad[B] = implicitly[Monad[B]]
but this gets stuck in a infinite loop at runtime, I suppose because implicitly
itself relies on an the corresponding implicit value. I guess I need to say that the implicit value for Monad[B]
is actually the same as the implicit value for Monad[List]
, since B[_] = List[_]
. But unfortunately,
implicit def monadB: Monad[B] = implicitly[Monad[List]]
doesn't work either, because Monad is invariant in it's type parameter (which, if I get it, means that Monad[List] can't be used in place of Monad[B], even though B = List).
I'm stuck. How do I define monadB
?