何时使用isInstanceOf和何时使用大小写匹配语句(在Scala中)? [英] When to use isInstanceOf and when to use a match-case-statement (in Scala)?

查看:125
本文介绍了何时使用isInstanceOf和何时使用大小写匹配语句(在Scala中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sealed class A
class B1 extends A    
class B2 extends A

假设我们有一个类A的对象的列表: val l:List [A] = List(新B1,新B2,新B1,新B1)

Assuming we have a List of objects of class A : val l: List[A] = List(new B1, new B2, new B1, new B1)

我们要过滤掉B1类型的元素. 然后我们需要一个谓词,并可以使用以下两种替代方法:

And we want to filter out the elements of the type B1. Then we need a predicate and could use the following two alternatives:

l.filter(_.isInstanceOf[B1])

l.filter(_ match {case b: B1 => true; case _ => false})

我个人更喜欢第一种方法,但是我经常阅读,应该更频繁地使用match-case语句(出于我不知道的原因).

Personally, I like the first approach more, but I often read, one should use the match-case statement more often (for reasons I do not know).

因此,问题是:使用isInstanceOf而不是match-case语句是否有缺点?什么时候应该使用哪种方法(以及在这里应该使用哪种方法,为什么?)?

Therefore, the question is: Are there drawbacks of using isInstanceOf instead of the match-case statement ? When should one use which approach (and which approach should be used here and why) ?

推荐答案

您可以像这样进行过滤:

You can filter like that:

l.collect{ case x: B1 => x }

IMO更具可读性.

这篇关于何时使用isInstanceOf和何时使用大小写匹配语句(在Scala中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆