为什么我不能在 Scala 中创建 F 有界对象 [英] Why I can't create F-bounded object in Scala

查看:22
本文介绍了为什么我不能在 Scala 中创建 F 有界对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

trait A[AA <: A[AA]]
//or even just `
trait A[AA]

这不起作用:

scala> object AAA extends A[AAA.type]
<console>:8: error: illegal cyclic reference involving object AAA
   object AAA extends A[AAA.type]
                        ^

但这有效:

scala> class AAA extends A[AAA]; object AAA extends AAA
defined class AAA
defined module AAA

做几乎(不完全)相同的工作.有什么原因吗?

Doing almost (not exactly) same and this works. Any reason?

附:还有,我能做什么在这样的对象内部强制编译器内部的无限循环?

P.S. And also, what exactly can I do inside such object to force infinte cycle inside the compiler itself?

推荐答案

正如您在标题中提到的,工作案例 class AAA extends A[AAA]F-bounded polymorphism,这是一个递归类型定义,其中定义引用自身.递归在类型中相当普遍,即使是不起眼的 List 也是递归的;这是一个很好理解的领域.

As you allude to in your title, the working case class AAA extends A[AAA] is an example of F-bounded polymorphism, which is a recursive type definition where the definition refers to itself. Recursion is fairly common in types, even the humble List is recursive; it's fairly well understood territory.

但是,object AAA extends A[AAA.type] 不是递归类型.这里 AAA 是一个 value,并且您的声明要求编译器在定义值时解析对值类型的引用,这不是 Scala 设计/预期的功能拥有.

However, object AAA extends A[AAA.type] is not a recursive type. Here AAA is a value, and your declaration asks the compiler to resolve the reference to a value's type while it is being defined, which is not a capability Scala was designed/intended to have.

这篇关于为什么我不能在 Scala 中创建 F 有界对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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