[英]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. 我想限制我的高级M
具有scalaz.Monad[M]
实例。 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. 但我希望M成为抽象类型成员。 Is this possible in Scala? 在Scala中这可能吗?
If you want to require a Monad[M]
instance, just... require it: 如果您需要Monad[M]
实例,只需...要求它:
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
; 不幸的是,如果仅通过val m = implicitly
实现类,则必须指定m。 the only way around that is the abstract class
approach you mention. 唯一的解决方法是您提到的abstract class
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.