Scala自我类型可以强制案例类类型吗

编程入门 行业动态 更新时间:2024-10-10 10:32:21
本文介绍了Scala自我类型可以强制案例类类型吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在scala中,有没有办法将特征的自身类型定义为案例类,例如任何案例类"?我希望自类型能够使用案例类的.copy方法,并强制其自身类型为 some 案例类,而不是常规类.我认为结构性类型无济于事,因为它们需要包含特定参数的签名(对于任何案例类,我可能一般都不能使用结构性类型).

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).

请放弃如果您需要做某些错误的事情",因为我已经讲过,但是我的api设计-如果可以的话,将会变得很笨拙.我也很好奇下次.

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.

推荐答案

这仅适用于(根据您的建议)结构类型,并且仅适用于案例类参数类型的已知固定序列(您需要使用的确切签名) copy).例如:

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)

更多推荐

Scala自我类型可以强制案例类类型吗

本文发布于:2023-11-25 17:55:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630744.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   自我   案例   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!