Scala将类型参数传递给对象 [英] Scala passing type parameters to object

查看:58
本文介绍了Scala将类型参数传递给对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala v 2.7.7 中

In Scala v 2.7.7

我有一个文件

class Something[T] extends Other

object Something extends OtherConstructor[Something]

这会引发错误:

class 有些东西接受类型参数
object 某物扩展了 OtherConstructor[Something] {

class Something takes type parameters
object Something extends OtherConstructor[Something] {

但是,我不能这样做

object Something[T] extends OtherConstructor[Something[T]]

它抛出一个错误:

It throws an error:

错误:';'预期但找到[".

error: ';' expected but '[' found.

是否可以将类型参数发送到对象?或者我应该改变并简单地使用Otherconstructor

Is it possible to send type parameters to object? Or should I change and simply use Otherconstructor

推荐答案

您可以使用:

object Something extends OtherConstructor[Something[_]]

您当然会受到存在类型的限制,该类型没有上限而不是具体类型.此解决方案可能没有意义,对于您关心的那些 T,例如

You will of course be restricted by having an existential type with no upper bound in place instead of a concrete type. This solution may not make sense and you might need one object per concrete type T, for those T's which you care about, e.g.

object StringSomething extends OtherConstructor[Something[String]]

但是这有一个(可能的)缺点,即 StringSomething 不是 Something 的伴随对象.

But then this has the (possible) disadvantage that StringSomething is not the companion object of Something.

然而,我的建议是不要开始搞乱设计通用 API(尤其是像上面这样的自我引用的 API),除非你真的,真的知道你在做什么是做.它几乎肯定会以泪水结束,并且有很多 CORE Java API 很糟糕,因为添加了泛型的方式(JTable 上的 RowSorter API 就是一个例子)

However, my advice would be don't start messing about designing generic APIs (especially self-referential ones like the above) unless you really, really know what you are doing. It will almost certainly end in tears and there are plenty of CORE Java API's which are terrible because of the way generics have been added (the RowSorter API on JTable being one example)

这篇关于Scala将类型参数传递给对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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