Scala casting and asInstanceOf exception

In the following code, is it possible to reformulate without using asInstanceOf? I found some advice on what asInstanceOf / isInstanceOf should be avoided and I was able to clean up my code except for the usage shown below.

I found a duplicate question here , but it didn't work for me in this particular case, or am I just too much of a beginner to translate this for my own use.

trait pet {}
class dog extends pet {
  def bark: String = {
    "WOOF"
  }
}

def test(what: pet) : String =
{
  what match {
    case _:dog =>
      val x = what.asInstanceOf[dog]
      x.bark
  }
}

test(new dog())

      

I tried for example:

val x = what : dog

      

but it doesn't work.

+3


source to share


1 answer


You can simply state in the case section that you expect dog

object:

case x: dog => x.bark

      



But now you can get scala.MatchError

if a non-dog object will be passed to your method. Therefore, you need to add a default case with the desired behavior like this:

case _ => "unknown pet"

      

+6


source







All Articles