简体   繁体   中英

In Scala how to check the runtime type of an object in base trait

I have a set of classes that filter objects of only a particular type.

trait FilterTrait {
    type RequiredType <: BaseType

    def filter(baseObjects: Seq[BaseType]): Seq[BaseType] = {
        val (requiredTypeObjects, nonRequiredTypeObjects) = baseObjects.partition(isOfRequiredType)

        nonRequiredTypeObjects ++ 
        filterRequiredType(requiredTypeObjects.asInstanceOf[Seq[RequiredType]])
    }

    def filterRequiredType(typeObjects: Seq[RequiredType]): Seq[RequiredType]

    def isOfRequiredType[A <: BaseType](aObj: A): Boolean = ???(to be implemented)
}

class AFilter extends FilterTrait {
    type RequiredType = CompoundType
    ...
}

class BFilter extends FilterTrait {
    type RequiredType = BaseType with ATrait
    ...
}

I tried implementing isOfRequiredType method in the base class:

def isOfRequiredType[A <: BaseType](aObj: A): Boolean = 
    classOf[RequiredType].isAssignableFrom(aObj.getClass)

I get the error "class type required but RequiredType found".

I can get this working by implementing isOfRequiredType in all the sub classes. But I was wondering whether there is a way to get this to work by implementing isOfRequiredType in the base trait.

It can be easier done if you can use abstract class, like this:

abstract class Filter[RequiredType<:BaseType:Manifest] {
   def isOfRequiredType[A <: BaseType](aObj: A): Boolean = 
       manifest[RequiredType].runtimeClass.isAssignableFrom(aObj.getClass)       

   ...
}

The code above uses manifests - which are supposed to be replaced with TypeTags in the future, howeve I don't have to much experience with this part of scala 2.10 so I stick with manifest version for now.

https://groups.google.com/forum/#!msg/scala-user/2X7pHwqd6_A/fOd1yyURIhEJ - here is discussion why it's not so easy with traits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM