简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM