Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

traits - can a scala self type enforce a case class type

Would there be any way in scala, to define a trait's self type to be a case class, as in "any case class"? I would like a self type to be able to use the .copy method of a case class, enforcing that its self type is some case class not a regular class. Structural types, I think, won't help, as they require a signature comprising specific arguments (I can probably not structural-type generically for any case class).

Please forgo the "if you need that you must be doing something wrong", as I've already moved on but my api design - will have been slicker if the above were possible. I am also curious for next times around.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This would only work using (as you suggest) structural types, and also only for a fixed known sequence of case class argument types (you need the exact signature of copy). For example:

trait InCase[Repr] {
  self: { def copy(foo: Int): Repr } =>

  def test(foo: Int): Repr = copy(foo)
}

case class Fail(foo: Int, bar: String) extends InCase[Fail] //illegal inheritance

case class Succeed(foo: Int) extends InCase[Succeed]

Succeed(123).test(456)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...