Search code examples
javascalacastinginstanceof

Scala: cast an object and assign it to a variable


I want to cast myObject to a specific class and assign it to a variable myTargetObject. I have the following Scala code, but there is error at the cast:

  def findResult[T](myObject: T): String = {

    var myTargetObject= None

    if (myObject.isInstanceOf[myClass1]) {
      myTargetObject = myObject.asInstanceOf[myClass1]

    } else if (myObject.isInstanceOf[myClass2]) {
      myTargetObject = myObject.asInstanceOf[myClass2]

    } else (myObject.isInstanceOf[myClass3]) {
      myTargetObject = myObject.asInstanceOf[myClass3]
    }  
}

What should be the right syntax for this purpose? Thank you very much!


Solution

  • The problem is when you do var myTargetObject= None, it infers the type to be Option[Any] None, so trying to reassign it as myClassN is going to fail.

    The correct way to do this is with matching:

    def findResult[T](myObject: T): String = {
      myObject match{
        case myTargetObject:MyClass1 => {
          //Actions for MyClass1
        }
        case myTargetObject:MyClass2 => {
          //Actions for MyClass2
        }
        case myTargetObject:MyClass3 => {
          //Actions for MyClass3
        }
        case other => {
          //Default action
        }
      }
    }
    

    This will let you use it as the desired type, while still being completely type-safe. Even this is still less than ideal though, since you don't generally want behavior to be specialized for each class in the calling code. You should try to refactor this into using common interfaces, so that it can all be handled in the same way.