如何在Scala中为特定的Map类型创建类型别名

Jon*_*ray 6 types scala map

我有一堆使用Map [String,Float]的代码.所以我想做

type DocumentVector = Map[String, Float]
...
var vec = new DocumentVector
Run Code Online (Sandbox Code Playgroud)

但这不编译.我收到消息:

trait Map is abstract; cannot be instantiated
[error]       var vec = new DocumentVector
Run Code Online (Sandbox Code Playgroud)

好的,我想我明白这里发生了什么.Map不是具体的类,只是通过()生成一个对象.所以我能做到:

object DocumentVector { def apply() = { Map[String, Float]() } }
...
var vec = DocumentVector()
Run Code Online (Sandbox Code Playgroud)

虽然它有点笨重,但是有效.但现在我想嵌套这些类型.我想写:

type DocumentVector = Map[String, Float]
type DocumentSetVectors = Map[DocumentID, DocumentVector]
Run Code Online (Sandbox Code Playgroud)

但这给出了同样的"无法实例化"的问题.所以我可以尝试:

object DocumentVector { def apply() = { Map[String, Float]() } }
object DocumentSetVectors { def apply() = { Map[DocumentID, DocumentVector]() } }
Run Code Online (Sandbox Code Playgroud)

但是DocumentVector实际上不是一个类型,只是一个带有apply()方法的对象,所以第二行不会编译.

我觉得我错过了一些基本的东西......

Jam*_*Iry 8

只是要具体说明你想要哪种地图

scala> type DocumentVector = scala.collection.immutable.HashMap[String,Float]
defined type alias DocumentVector

scala> new DocumentVector                                                    
res0: scala.collection.immutable.HashMap[String,Float] = Map()
Run Code Online (Sandbox Code Playgroud)

除非你需要抽象Map类型的灵活性,否则没有比从工厂分离类型别名更好的解决方案(可以是普通方法,不需要带有apply的Object).


dre*_*xin 7

我同意@missingfaktor,但我会实现它有点不同,所以感觉就像使用一个伴随特征:

type DocumentVector = Map[String, Float]
val DocumentVector = Map[String, Float] _

// Exiting paste mode, now interpreting.

defined type alias DocumentVector
DocumentVector: (String, Float)* => scala.collection.immutable.Map[String,Float] = <function1>

scala> val x: DocumentVector = DocumentVector("" -> 2.0f)
x: DocumentVector = Map("" -> 2.0)
Run Code Online (Sandbox Code Playgroud)