如何在Scala中为特定的Map类型创建类型别名
发布时间:2020-12-16 19:09:46 所属栏目:安全 来源:网络整理
导读:我有一堆使用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 [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). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |