Attempting to model F-bounded polymorphism as a type member in Scala

巧了我就是萌 提交于 2019-11-28 23:29:43

I think this is an example of what you are looking for:

sealed trait Event { self =>
  type E >: self.type <: Event
  def instance: E = self
}

case class UserJoined() extends Event {
  type E = UserJoined
}

case class UserLeft() extends Event {
  type E = UserLeft
}

If you would like to read more, this snippet is from a recent post that covers related concepts.

Edit: To complete the answer, it would be:

scala> trait Foo extends Product with Serializable with Event{}
defined trait Foo

scala> case class X() extends Foo {
     |     type Self = X
     |     def bar = this
     |   }
defined class X

scala> case class Y() extends Foo {
     |     type Self = Y
     |     def bar = this
     |   }
defined class Y

scala> List(X(),Y())
res9: List[Foo] = List(X(), Y())

scala>   def tester[A: TC](x: Seq[A]) = "foo"
tester: [A](x: Seq[A])(implicit evidence$1: TC[A])String

scala>  tester(Seq(X(), Y()))
res10: String = foo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!