Scala:解决“非法循环引用" [英] Scala: working around the "illegal cyclic reference"

查看:31
本文介绍了Scala:解决“非法循环引用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个基于 HashMap 的树,该树支持对给定根键的 O(1) 子树查找.为了这个目标,我正在努力做到以下几点:

I'm trying to implement a HashMap-based tree that'd support O(1) subtree lookup for a given root key. To that goal, I'm trying to do the following:

scala> type Q = HashMap[Char, Q]
<console>:6: error: illegal cyclic reference involving type Q
       type Q = HashMap[Char, Q]
                          ^

所以问题是,有没有办法让我做这样的事情而不诉诸丑陋的 HashMap[Char, Any] 以及随后将值转换为 HashMap[Char,任何]?

So the question is, is there a way for me to do something of the sort without resorting to the ugly HashMap[Char, Any] with subsequent casting of values to HashMap[Char, Any]?

现在,我也看到我可以使用类似下面的东西来避免循环引用错误,它甚至可能更干净——但最好能找出如何正确地以第一种方式做到这一点,只是为了教育价值.

Now, I also see that I can use something like the following to avoid the cyclic-reference error, and it might even be cleaner -- but it'd be nice to find out how to correctly do it the first way, just for the educational value.

import collections.mutable.HashMap

class LTree {
  val children = new HashMap[Char, LTree]
}

非常感谢.

推荐答案

我可能没有明白"这个问题,但是呢

I probably don't "get" the question, but what about

class L {
  type Q = java.util.HashMap[Char, this.type]
}

class Q extends java.util.HashMap[Char, Q]

这篇关于Scala:解决“非法循环引用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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