假设
class SpecificAPI extends APIConnection{
def annotate(...) = //definition of annotate function
}
我有一个班主任:
class Father{
protected def processMessage[A<:APIConnection](recordToAnalyze: RecordToAnalyze, api:Option[A] = None): Option[IndexEnrichment]
}
class Child extends Father{
override def processMessage[SpecificAPI](recordToAnalyze: RecordToAnalyze, api: Option[SpecificAPI]): Option[IndexEnrichment] = {
api.get.annotate(...) //I cannot access to this function
}
为什么我无法访问Child类中SpecificAPI
的方法?
基本上我想定义一个泛型方法来实例化与不同API的连接,我想只更改Children类中的函数processMessage
。我错过了什么吗?
答案 0 :(得分:1)
因为类SpecificAPI
中的Child
是类型参数。所以它与实际输入processMessage[A]
...
你可能想要的是将类型参数提升到类定义,这样你就可以将SpecificApi
传递给Child
:
class Father[A<:APIConnection]{
protected def processMessage(recordToAnalyze: RecordToAnalyze, api:Option[A] = None): Option[IndexEnrichment]
}
class Child extends Father[SpecificAPI]{
override def processMessage(recordToAnalyze: RecordToAnalyze, api: Option[SpecificAPI]): Option[IndexEnrichment] = {
api.get.annotate(...) //I cannot access to this function
}
作为旁注,请不要直接在Option
上使用get,除非你只是为了做这个例子。
答案 1 :(得分:1)
SpecificAPI
类的processMessage
中的类型参数Child
是一个无约束的类型参数,名称极其混乱。如果您想更好地了解代码的作用,请将其重命名为X
:
class Child extends Father{
override def processMessage[X](
recordToAnalyze: RecordToAnalyze,
api: Option[X]
): Option[IndexEnrichment] = {
api.get.annotate(...) //I cannot access to this function
// Well, why should an arbitrary `X` have method `annotate`?
}
}
现在很明显,这无法编译。
我有一种模糊的感觉,你可能有这样的意思:
trait APIConnection
class IndexEnrichment
class RecordToAnalyze
class SpecificAPI extends APIConnection {
def annotate(): Unit = ???
}
trait Father [A <: APIConnection] {
protected def processMessage(
recordToAnalyze: RecordToAnalyze,
api:Option[A] = None
): Option[IndexEnrichment]
}
class Child extends Father[SpecificAPI] {
override def processMessage(
recordToAnalyze: RecordToAnalyze,
api: Option[SpecificAPI]
): Option[IndexEnrichment] = {
api.get.annotate()
???
}
}