假設我們有一個abstract class(同樣的問題traits):
abstract class TypeParser[C <: Changes : TypeTag] extends Serializable {
val enrichmentType: EnrichmentType
protected def parseChanges(row: Row): C
}
實作如下所示:
object PlaceholderParser extends TypeParser[PlaceholderChanges] {
val enrichmentType: EnrichmentType = PlaceholderType
override protected def parseChanges(row: Row): PlaceholderChanges = ???
}
上面的實作是一個單例,但是,在以后的實作中不能強制它是一個單例。因此,可以簡單地將其實作為class,例如:
class PlaceholderParser2() extends TypeParser[PlaceholderChanges2] {
val enrichmentType: EnrichmentType = PlaceholderType2
override protected def parseChanges(row: Row): PlaceholderChanges2 = ???
}
有沒有辦法強制實作成為單例?
附帶問題:強迫它有什么好處嗎?
uj5u.com熱心網友回復:
為了我們的優勢,所有人都objects擴展了一個名為Singleton. 您不能直接擴展它,但我們可以使用稱為self-types的Scala特性來強制 to 的所有子型別也是(即)TypeParserSingletons objects
abstract class TypeParser[C <: Changes : TypeTag] extends Serializable {
self: Singleton =>
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496930.html
上一篇:ClassCastException:org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema不能被強制轉換
