简体   繁体   English

Scala转换并避免asInstanceOf

[英]Scala casting and avoiding asInstanceOf

In the following code, is it possible to reformulate without using asInstanceOf? 在下面的代码中,是否可以在不使用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. 我找到了一些样式指南建议asInstanceOf / isInstanceOf应该避免,我设法清理我的代码,除了下面显示的用法。

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: 您可以在案例部分中指定您期望的dog对象:

case x: dog => x.bark

But now you might receive scala.MatchError if non-dog object will be passed to your method. 但是现在如果将非dog对象传递给您的方法,您可能会收到scala.MatchError So you need to add default case with desirable behavior like this: 因此,您需要添加具有所需行为的默认情况,如下所示:

case _ => "unknown pet"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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