Scala:使用其内部类型之一对类型进行参数化 [英] Scala : parameterize a type with one of its inner types

查看:34
本文介绍了Scala:使用其内部类型之一对类型进行参数化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用其子类之一对类型进行参数化.请考虑以下内容:

I would like to parameterize a type with one of its subclasses. Consider the following:

class DataLoader {
  class Data { /* data specifics to this data loader */ }
  def getData : Data /* and so on */
}

现在,我想使此加载程序能够从网络异步检索数据.一种选择是使它成为Callable的子类.

Now I want to make this loader able to asynchronously retrieve data from the network. One of the options is to have it subclass Callable.

class DataLoader extends Callable[Data] {
  class Data { /* ... */ }
  def call : Data = { ... }
}
val futureData = executor.submit(new DataLoader)
futureData.get

Scala不允许我这样做,因为当我提供Callable的参数时,数据还未知.如果我写DataLoader.Data,Scala会要求我进行循环引用.

Scala will not let me do that, because when I supply the parameters of Callable, Data is not known yet. If I write DataLoader.Data, Scala calls me off for a cyclic reference.

当然,我可以在装载程序之外编写数据类,但是在某些情况下,它的内部更好.当然,另一个选择是拥有一个DataManager,该数据管理器内部具有一个数据类型和一个扩展Callable [Data]的加载程序-在这种情况下,这可以说是更好的设计.但是除了那些问题之外,我有什么办法可以真正实现一个特征,即编写返回T的函数,将T设置为内部类?

Sure, I could write my data class outside of my loader, but there are cases where it's nicer inside. Sure, another alternative would be to have, say, a DataManager, with inside a Data type and a Loader which extends Callable[Data] - which in this case is arguably better design. But those issues aside, is there any way I can actually implement a trait that involves writing a function returning a T, setting T to be an inner class ?

推荐答案

有一百种方法可以实现合理的目标,因此很难知道如何回答.我认为您不想太喜欢在子类型自己的内部类之一上参数化超类型的想法.即使有效,也不会.

There are a million ways to achieve something reasonable, so it's hard to know how to answer. I don't think you want to get too attached to the idea of parameterizing a supertype on one of the subtype's own inner classes. Even if it works, it won't.

在数百万种方法中,我随机选择了一些东西,结果却涉及到倒置.我这样做是因为您在评论中说您无法将其编译到伴随对象中,而且我不确定为什么会这样.

Out of the million ways I picked something at random and it turned out to involve inversion. I did it this way because you said in a comment you couldn't get it to compile in the companion object, and I'm not sure why that would be.

import java.util.concurrent.Callable

class DataLoader extends Callable[DataLoader.Data] {
  def call = new DataLoader.Data(this)
}

object DataLoader {
  private class Data(loader: DataLoader) {
  }
}

这篇关于Scala:使用其内部类型之一对类型进行参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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