简体   繁体   中英

Scala casting and avoiding asInstanceOf

In the following code, is it possible to reformulate without using asInstanceOf? I found some styleguide suggestions that asInstanceOf/isInstanceOf should be avoided, and I managed to clean up my code except for the usage shown below.

I did find a duplicate question here , but it didn't really help me for this particular case, or I'm just too much of a beginner to translate it to my own use case.

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 that doesn't seem to work.

You can just specify in case section that you expect dog object:

case x: dog => x.bark

But now you might receive scala.MatchError if non-dog object will be passed to your method. So you need to add default case with desirable behavior like this:

case _ => "unknown pet"

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