Scala中的类别名 [英] Class alias in 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
.
您仍然可以使用类型$对其进行别名c $ c>关键字:
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屋!