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



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

type DocumentVector = Map[String, Float]
...
var vec = new DocumentVector

但这不会编译。我收到消息:

trait Map is abstract; cannot be instantiated
[error]       var vec = new DocumentVector

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

object DocumentVector { def apply() = { Map[String, Float]() } }
...
var vec = DocumentVector()

这是有效的,尽管它有点笨重。但现在我想嵌套类型。我想写:

type DocumentVector = Map[String, Float]
type DocumentSetVectors = Map[DocumentID, DocumentVector]

但这也带来了同样的"无法实例化"问题。所以我可以试试:

object DocumentVector { def apply() = { Map[String, Float]() } }
object DocumentSetVectors { def apply() = { Map[DocumentID, DocumentVector]() } }

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

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

只需具体说明您想要的地图类型

scala> type DocumentVector = scala.collection.immutable.HashMap[String,Float]
defined type alias DocumentVector
scala> new DocumentVector                                                    
res0: scala.collection.immutable.HashMap[String,Float] = Map()

除非您需要抽象Map类型的灵活性,否则在这种情况下,没有比将类型别名与工厂分离更好的解决方案了(这可能是一种简单的方法,不需要带apply的Object)。

我同意@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)

普通方法怎么样?

type DocumentVector = Map[String, Float]
def newDocumentVector = Map[String, Float]()
type DocumentSetVectors = Map[DocumentID, DocumentVector]
def newDocumentSetVectors = Map[DocumentID, DocumentVector]() 

这可能是的一个可能解决方案

package object Properties {
  import scala.collection.generic.ImmutableMapFactory
  import scala.collection.immutable.HashMap
  type Properties = HashMap[String, Float]
  object Properties extends ImmutableMapFactory[Properties] {
    def empty[String, Float] = new Properties()
  }
}

相关内容

最新更新