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

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

问题描述

假设我有:

  trait A [AA <:A [AA]] 
//或即使只是'
trait A [AA]

这不起作用:

  scala>对象AAA扩展A [AAA.type] 
< console> 8:错误:涉及对象AAA的非法循环引用
对象AAA扩展A [AAA.type]
^

但是这样做:

 阶> AAA级延伸A [AAA];对象AAA扩展AAA 
定义类AAA
定义模块AAA

不完全)相同,这工作。任何理由?



此外,我可以做些什么 在这样的对象内迫使编译器本身内部的infinte循环? 解析方案

正如你在你的标题中提到的那样,工作案例 class AAA extends A [AAA] F-bounds多态性,这是一个定义引用自身的递归类型定义。递归在类型中相当常见,即使是不起眼的列表递归;它是相当好理解的领土。



但是,对象AAA扩展A [AAA.type] 不是递归类型。这里 AAA 是一个,并且您的声明要求编译器在定义时解析对值类型的引用,而不是功能Scala被设计/打算拥有。


Suppose I have:

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

This doesn't work:

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

But this works:

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?

解决方案

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.

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-bound对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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