Scala中的类别名 [英] Class alias in scala

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

问题描述

是否可以在Scala中将 MyAlias [A] 定义为 MyClass [String,A] 的别名。例如, MyAlias [Int] 将引用 Map [String,Int]

Is it possible in Scala to define MyAlias[A] as an alias for MyClass[String, A]. For example, MyAlias[Int] would refer to Map[String, Int].

推荐答案

请注意,地图特征 ,而不是

Note that Map is a trait, not a class.

您仍然可以使用类型关键字:

You can still alias it using the type keyword:

type StringMap[A] = Map[String, A]

val myMap: StringMap[Int] = Map("a" -> 1)

对象特征范围内完成定义(以及在任何方法或表达式的范围内)。

This can be done within the scope of a class, object or trait definition (and in the scope of any method or expression).

有时,您希望别名对于其声明范围是私有的,纯粹是为了方便您实现码。如果您希望该类型通常可用,则包装对象很有用:

Sometimes you'll want the alias to be private to its declaring scope, purely as a convenience for your implementation code. If you want the type to be usable generally, Package Objects come in useful:

package object mypackage {
  type StringMap[A] = Map[String, A]
}

因为 Map 是一个特征(以及相关的伴随对象)(而不是类),您将无法直接使用它来创建实例:

Because Map is a trait (and associated companion object) and not a class, you won't be able to use it directly to create instances:

val myMap = new StringMap[Int]
// error: trait Map is abstract; cannot be instantiated

但是,如果您为类命名,您仍然可以使用 new 关键字:

If you alias a class, though, you can still use the new keyword:

type StringHashMap[A] = HashMap[String, A]
val myMap = new StringHashMap[Int]

这篇关于Scala中的类别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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