何时使用选项 [英] When to use Option

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

问题描述

我学习Scala有一段时间了,并不能清楚地理解Option的用法.它帮助我在链接函数时避免空检查(根据 docs).这对我来说很清楚:)

I learn Scala for some time and can't clearly understand the usage of Option. It helps me to avoid null checks when I chain functions (according to docs). That's clear for me :)

接下来我看到 Option 可以作为开发人员的一种指示符,表明此处可能存在空值并且必须对其进行处理.这是真的吗?如果是,我应该尽可能使用 Option 吗?例如

Next I see that Option can be kind of indicator for developer that null value is possible here and it must be handled. Is it true? If yes should I use Option whereever it's possible? For example

class Racer {
    val car = new Car()
}

我有 Racer 类,并且我确定 car 字段不能为空(因为它是常量并且在我创建 Racer 实例时获得一个值).此处无需 Option.

I have Racer class and I'm sure that car field can't be null (because it's constant and get a value when I create Racer instance). No need for Option here.

class Racer {
    var car = new Car()
}

我这样做是为了让汽车可以改变.并且有人可以将 null 分配给 car.我应该在这里使用 Option 吗?如果是,我注意到我所有的类字段都是 Option 的候选者.我的代码看起来像这样

Here I make it so that the car can change. And it's possible for someone to assign null to car. Should I use Option here? If yes I notice that all my class fields are candidates for Option. And my code looks like this

class Racer {
    var car: Option[Car] = None
    var currentRace: Option[Race] = None
    var team: Option[Team] = None
    ...
}

好看吗?对我来说,这似乎是一种过度使用的选项.

Does it look good? For me it seems kind of Option overusing.

def foo(): Result = {
    if( something )
        new Result()
    else
        null
}

我有一个可以返回空值的方法.我应该返回 Option 吗?如果方法可能返回 null,我应该总是这样做吗?

I have a method which can return null. Should I return Option instead? Should I always do it if it's possible for method to return null?

任何关于它的想法都会有所帮助.提前致谢!

Any thoughts about it would be helpful. Thanks in advance!

我的问题类似于为什么选择,但我认为不一样.更多的是关于何时,而不是为什么. :)

My question is similiar to Why option but I think it's not the same. It's more about when, not why. :)

推荐答案

在 Scala 中应尽可能避免 null.它实际上只是为了与 Java 的互操作性而存在.因此,当函数或方法可能返回无值"时,或者当成员变量具有无值"在逻辑上有效时,请使用 Option 而不是 null值".

You should avoid null as much as possible in Scala. It really only exists for interoperability with Java. So, instead of null, use Option whenever it's possible that a function or method can return "no value", or when it's logically valid for a member variable to have "no value".

关于您的 Racer 示例:如果 Racer 没有 carcurrentRace<,它是否真的有效/code> 和 团队?如果没有,那么你不应该做那些成员变量选项.不要只是让它们成为选项,因为理论上可以将它们分配给 null;只有在逻辑上你认为它是一个有效的 Racer 对象时才这样做,如果这些成员变量中的任何一个没有值.

With regard to your Racer example: Is a Racer really valid if it doesn't have a car, currentRace and team? If not, then you shouldn't make those member variables options. Don't just make them options because it's theoretically possible to assign them to null; do it only if logically you consider it a valid Racer object if any of those member variables has no value.

换句话说,最好假装 null 不存在.在 Scala 代码中使用 null 是一种代码味道.

In other words, it's best to pretend as if null doesn't exist. The use of null in Scala code is a code smell.

def foo(): Option[Result] = if (something) Some(new Result()) else None

请注意,Option 有许多有用的方法可以使用.

Note that Option has many useful methods to work with.

val opt = foo()

// You can use pattern matching
opt match {
  case Some(result) => println("The result is: " + result)
  case None         => println("There was no result!")
}

// Or use for example foreach
opt foreach { result => println("The result is: " + result) }

另外,如果你想以函数式风格编程,你应该尽可能避免可变数据,这意味着:避免使用var,使用val相反,请使用不可变集合并使您自己的类尽可能不可变.

Also, if you want to program in the functional style, you should avoid mutable data as much as possible, which means: avoid the use of var, use val instead, use immutable collections and make your own classes immutable as much as possible.

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

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