Class alias in scala

做~自己de王妃 提交于 2019-11-30 01:59:40

问题


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].


回答1:


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]
}

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

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

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


来源:https://stackoverflow.com/questions/10830308/class-alias-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!