Marius Danila
Marius Danila

Reputation: 10401

How to constrain type as abstract type member in trait?

I would like to define the following trait with an abstract type:

trait C {
  type M[_]

  def doSomething(m: M[T]): M[T] = ???
  def somethingElse: M[T] = ???
}

I'd like to constrain my higher type M to have a scalaz.Monad[M] instance. One solution would be to change my code like:

abstract class C[M: Monad] { ... }

but I would like M to be an abstract type member. Is this possible in Scala?

Upvotes: 1

Views: 95

Answers (1)

lmm
lmm

Reputation: 17431

If you want to require a Monad[M] instance, just... require it:

trait C {
  type M[_]
  /*implicit if you like*/ def m: Monad[M]
  ...
}

Implementing classes will unfortunately have to specify m, if only as val m = implicitly; the only way around that is the abstract class approach you mention.

Upvotes: 1

Related Questions