我具有以下特征和类(实际上这是一种简化,真正的代码是用 Java 编写的,不在我的控制范围内):
trait BusinessTermValue {
def getValue: Any
}
class BusinessTermValueImpl(override val getValue: Any) extends BusinessTermValue
现在我正在尝试改进我的 API 而不触及原始代码(Pimp My Library 模式):
package object businessterms {
implicit final class BusinessTermValueSupport(val btv: BusinessTermValue) extends AnyVal {
def isDefined(): Boolean = btv != null && btv.value != null
def isEmpty(): Boolean = isDefined() && (btv.value match {
case s: String => s.isEmpty
case l: Traversable[_] => l.isEmpty
case c: java.util.Collection[_] => c.isEmpty
case _ => false
})
def getAs[T](): T = btv.value.asInstanceOf[T]
}
object BusinessTerm {
def apply(value: Any): BusinessTermValue = new BusinessTermValueImpl(value)
}
}
它工作得很好:
println(BusinessTerm("A String").isEmpty) // false
println(BusinessTerm(1).isEmpty) // false, Int can't be empty
println(BusinessTerm(new Integer(1)).isEmpty) // false, Integer can't be empty
println(BusinessTerm(List(1, 2, 3)).isEmpty) // false
println(BusinessTerm(List(1, 2, 3).asJava).isEmpty) // false
println(BusinessTerm("").isEmpty) // true
println(BusinessTerm(List()).isEmpty) // true
println(BusinessTerm(Seq()).isEmpty) // true
println(BusinessTerm(Map()).isEmpty) // true
println(BusinessTerm(List().asJava).isEmpty) // true
仍然是模式匹配isEmpty
很麻烦。理想情况下,我想使用结构类型并确保实现的任何类型都isEmpty
适用于我的 API。
不幸的是,下面的代码不起作用。该变量e
匹配任何类型,即使value
没有定义isEmpty
:
def isEmpty(): Boolean = isDefined() && (btv.value match {
case e: { def isEmpty(): Boolean } => e.isEmpty
case _ => false
})
有没有办法isEmpty
仅在底层value
实现时委托?