Scala避免使用null [英] Scala avoid using null

查看:47
本文介绍了Scala避免使用null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在github上拥有一个由 codacy 分析的项目.分析建议对于以下代码行避免使用空值" :

I hava a project on github that is analysed by codacy . The analysis suggest to "Avoid using null" for the following line of code:

def doSomethingWithPath(path:Path) = {
    require(path != null, "Path should not be null") //<-to avoid
    ...
}

最简单的Scala惯用语言来修复它是什么?

What is the simplest scala idiomatic thing to do to fix it?

推荐答案

我会保持原样.您实际上并没有在这里使用null,只是要提防它.另一种选择是完全删除该行,并决定根本不处理null.在构建良好的代码库中忽略空值的可能性可能很好,在这种情况下,无论如何都不应该出现空值,并且空值将是一个错误,但是简单的防护措施可以防止在某些情况下出现错误时出现更多细微的错误,并且实际发生空值.

I would keep it as is. You aren't really using null here, just guarding against it. The alternative could be to just delete that line altogether, and decide to not handle the null at all. Ignoring the possibility of null might be fine in a well built code base where it shouldn't come up anyway and null would be a bug, but a simple guard to catch it could prevent more subtle bugs from showing up in case something went wrong and null actually happens.

这篇关于Scala避免使用null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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