我有以下的scala代码。将子类作为参数传递给具有超类作为参数的函数的参数
trait Super
case class Sub(value:String) extends Super
case class YetAnotherSub(value:String) extends Super
case class OnlyErrorType(value:String) extends Super
def function1[I <: Super, R](mapper : (I) => R, input: Super) (default: R): R = input match {
case error: OnlyErrorType =>
default
case success: I => mapper(success) // Ideally success => mapper(success)
case _ => default // I don't want this line at all, as I'm not expecting any other type
}
def function2(input:String):Super = if(input.size >= 3) Sub("Greater") else OnlyErrorType("Lesser")
def function3(input:String):String = {
val result = function2(input)
function1({sub:Sub => sub.value.toUpperCase}, result) ("Empty Result")
}
function3("Input")
有各种功能类似于function2
它接受一些参数和返回的Super
任何亚型。我想有一个通用的映射器,像function1
,类型为Super
映射到一些其他类型的,但在OnlyErrorType
换句话说情况下返回默认值,我想有一些默认处理为OnlyErrorType
,但让调用函数(在此例中为function3
)指定SuccessType的映射(除OnlyErrorType
之外的Super
的任何子类型)。
我该如何做到这一点?
上面的代码编译,但我讨厌看到警告,
warning: abstract type pattern I is unchecked since it is eliminated by erasure
我觉得必须有一个更好的方式来做到这一点。
我会喜欢你的第一个建议,如果它的工作。它不会编译。 – nobody
修正了这个建议。 –