我需要组合Enumeration
的一些值。斯卡拉枚举和值组
下面是代码:
object PostType extends Enumeration {
// Documents
val BOOKMARK = Value("bookmark")
val FILE = Value("file")
val NOTE = Value("note")
val WIKIDOC = Value("wikidoc")
…
}
object PostTypes {
type PostTypes = List[PostType.Value]
val DOCUMENTS : PostTypes = List(PostType.BOOKMARK, PostType.FILE, PostType.NOTE, PostType.WIKIDOC)
val QUESTIONS : PostTypes = List(PostType.QUESTION, PostType.QUICKPOLL, PostType.SURVEY)
val EVENT : PostTypes = List(PostType.EVENT)
…
val ALL : PostTypes = PostType.values.toList
}
有没有更好的办法? 下面是我看到的缺点:PostType.Value
和PostTypes.PostTypes
在客户端代码!
[更新]提高代码两者的帮助下回答
object PostType extends Enumeration {
// Documents
val Bookmark = Value("bookmark")
val File = Value("file")
val Note = Value("note")
val Wikidoc = Value("wikidoc")
…
}
object PostTypes {
import PostType._
implicit def toList(pt: Value) = List(pt)
type PostTypes = List[Value]
val Documents = List(Bookmark, File, Note, Wikidoc)
val Questions = List(Question, Quickpoll, Survey)
val All = values.toList
}
[更新2]的改进另一堆
object PostType extends Enumeration {
type PostType = Value
type PostTypes = List[Value]
implicit def toList(pt: Value) = List(pt)
// Documents
val Bookmark = Value(1, "bookmark")
val File = Value(2, "file")
val Note = Value(3, "note")
val Wikidoc = Value(12, "wikidoc")
// Declare after Val to avoid runtime error
val Documents = List(Bookmark, File, Note, Wikidoc)
val Questions = List(Question, Quickpoll, Survey)
val All = values.toList.sorted
}
而是通过导入PostType._来省略前缀(导入PostType.Value似乎没有做这项工作)? –
好点@YannMoisan –