我在Scala中很陌生。具有名为“ Document”的类和一些作为Document子级的类,例如“ Doc1”和“ Doc2”。所以:
abstract class Document(id: Int, xmlString: String) {
// make some operations and create an instance of subtype
}
case class Doc1 extends Document {
// some subclass specific methods
}
case class Doc2 extends Document {
// some subclass specific methods
}
Run Code Online (Sandbox Code Playgroud)
想要运行Document构造函数,结果由于传递了paramethers而有条件地创建Doc1或Doc2的实例。我应该在“文档”类中添加一些辅助构造函数吗?
任何想法欢迎。
最佳做法是使用伴随对象/单个对象:
abstract class Document { ... }
object Document {
def apply(docType: String) = {
if (docType == "doc1") {
Doc1()
} else {
Doc2()
}
}
}
Run Code Online (Sandbox Code Playgroud)
及其用法:
val document1 = Document("doc1")
Run Code Online (Sandbox Code Playgroud)
当然,这只是一个简单的示例-您可以将其更改docType为密封类,并通过模式匹配检查类型。
apply代替不同的函数名,因此您将编写Document("doc1")而不是Document.someFunctionName("doc1")| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |