Scala类型别名,包括伴随对象[初学者] [英] Scala type alias including companion object [beginner]

查看:261
本文介绍了Scala类型别名,包括伴随对象[初学者]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个类型别名来缩短,美观和封装的Scala代码. 假设我得到了一些集合,该集合具有作为地图列表的属性,其值是元组. 我的类型将编写List[Map[Int, (String, String)]]之类的内容,或者在我的应用程序允许的范围内编写更通用的内容.我可以想象有一个超类要求Seq[MapLike[Int, Any]]或任何使我的船浮起的东西,而具体的子类更为具体.

I'd like to write a type alias to shorten, nice and encapsulated Scala code. Suppose I got some collection which has the property of being a list of maps, the value of which are tuples. My type would write something like List[Map[Int, (String, String)]], or anything more generic as my application allows it. I could imagine having a supertype asking for a Seq[MapLike[Int, Any]] or whatever floats my boat, with concrete subclasses being more specific.

然后我想为这种长类型写一个别名.

I'd then want to write an alias for this long type.

class ConcreteClass {
  type DataType = List[Map[Int, (String, String)]]
  ...
}

然后我会在可以拿到的任何地方快乐地使用ConcreteClass#DataType并使用它.

I would then happily use ConcreteClass#DataType everywhere I can take one, and use it.

现在假设我添加了一个函数

Now suppose I add a function

def foo(a : DataType) { ... }

我想从外面用空列表调用它. 我可以调用foo(List()),但是当我想将基础类型更改为Seq的另一种类型时,我也必须返回并更改此代码.此外,此空列表不是很明确地用作DataType.并且伴随对象没有关联的List方法,因此我无法调用DataType()DataType.empty.当我需要非空列表时,这将更加烦人,因为我将不得不写出这种长类型的很大一部分.

And I want to call it from outside with an empty list. I can call foo(List()), but when I want to change my underlying type to be another type of Seq, I'll have to come back and change this code too. Besides, it's not very explicit this empty list is intended as a DataType. And the companion object does not have the associated List methods, so I can't call DataType(), or DataType.empty. It's gonna be even more annoying when I need non-empty lists since I'll have to write out a significant part of this long type.

为了缩短代码并对其加黑框,是否有任何方法可以让Scala将我的类型理解为同一事物,包括附带对象及其创建者方法? 或者,为什么我不应该首先这样做呢?

Is there any way I can ask Scala to understand my type as the same thing, including companion object with its creator methods, in the interest of shortening code and blackboxing it ? Or, any reason why I should not be doing this in the first place ?

推荐答案

答案实际上非常简单:

class ConcreteClass {
  type DataType = List[String]
}
object ConcreteClass {
  val DataType = List
}
val d = ConcreteClass.DataType.empty

这使我的代码可以调用ConcreteClass.DataType来构造具有List中所有方法的列表,而无需花费任何精力.

This enables my code to call ConcreteClass.DataType to construct lists with all the methods in List and little effort.

非常感谢Oleg的真知灼见.如果您不想委派列出对ConcreteClass.DataType的任何调用,而是精确控制您希望允许调用者执行的操作,那么他的答案也是最好的.

Thanks a lot to Oleg for the insight. His answer is also best in case you want not to delegate to List any call to ConcreteClass.DataType, but control precisely what you want to allow callers to do.

这篇关于Scala类型别名,包括伴随对象[初学者]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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