如何在 Scala 中用反射来沮丧?
How to downcast with reflection in Scala?
假设我有一个非密封特征 A
并且需要一个函数 convert[T <: A]: A => Option[T]
:
def convert[T <: A](a: A): Option[T] = // don't compile
if (a is instance of T) then Some(a) else None
您建议如何实施 convert
?
P.S 我不喜欢 reflection
但需要处理使用它的遗留问题。
而不是isInstance
,您可以在匹配表达式中使用ClassTag
,这稍微更清楚:
def convert[T <: A](a: A)(implicit ct: ClassTag[T]) = a match {
case ct(t) => Some(t)
case _ => None
}
假设我有一个非密封特征 A
并且需要一个函数 convert[T <: A]: A => Option[T]
:
def convert[T <: A](a: A): Option[T] = // don't compile
if (a is instance of T) then Some(a) else None
您建议如何实施 convert
?
P.S 我不喜欢 reflection
但需要处理使用它的遗留问题。
而不是isInstance
,您可以在匹配表达式中使用ClassTag
,这稍微更清楚:
def convert[T <: A](a: A)(implicit ct: ClassTag[T]) = a match {
case ct(t) => Some(t)
case _ => None
}