对象上的Scala F有界多态性 [英] Scala F-bounded polymorphism on object

查看:53
本文介绍了对象上的Scala F有界多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 Scala 中编写以下 F 有界多态性.为什么?

I cannot write the following F-bounded polymorphism in Scala. Why?

trait X[T <: X[T]]
object Y extends X[Y]

如何表达并编译它?

推荐答案

看来你真的应该会写,

trait X[T <: X[T]]
object Y extends X[Y.type]

然而,如果你尝试编译器会给你一个无益的(我认为是虚假的)错误,

however, if you try that the compiler will give you an unhelpful (and I think spurious) error,

scala> object Y extends X[Y.type]
<console>:16: error: illegal cyclic reference involving object Y
       object Y extends X[Y.type]

我说虚假"是因为我们可以用一些额外的基础设施来构造一个等效的对象,

I say "spurious" because we can construct an equivalent object with a little bit of additional infrastructure,

trait X[T <: X[T]]

trait Fix { type Ytype >: Y.type <: Y.type; object Y extends X[Ytype] }
object Fix extends Fix { type Ytype = Y.type }
import Fix.Y

如果您想在实际代码中对此进行试验,使用包对象代替 object Fix 会使这个习语更有用.

If you wanted to experiment with this in real code, using a package object in place of object Fix would make this idiom a little more usable.

这篇关于对象上的Scala F有界多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆