什么是“?” 符号(问号)在 Scala 中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10040206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:05:03  来源:igfitidea点击:

What does a "?" symbol (question mark) mean in Scala?

scalasyntax

提问by zjffdu

I meet some scala code with "?" but do not know what it mean in scala, could anyone explain it to me ? Thanks.

我遇到了一些带有“?”的 Scala 代码 但不知道在 Scala 中是什么意思,谁能给我解释一下?谢谢。

And here's one example

这是一个例子

 def getJobId(conf: Configuration): String =
    ?(conf.get("scoobi.jobid")).getOrElse(sys.error("Scoobi job id not set."))

回答by Christian

For me it looks like the apply method of Option. Is there somewhere the following import statement in the code:

对我来说,它看起来像 Option 的 apply 方法。代码中是否有以下导入语句:

import Option.{apply => ?}

This means applyis imported as ?. From the doc of Option.apply:

这意味着apply被导入为? . 来自 Option.apply 的文档:

An Option factory which creates Some(x) if the argument is not null,
and None if it is null.

一个 Option 工厂,如果参数不为 null,则创建 Some(x),如果为 null,则创建
None。

The whole statement means then:

整个声明的意思是:

if conf.get("scoobi.jobid") is not equal null, assign this string, otherwise assign the string sys.error("Scoobi job id not set.") returns

如果 conf.get("scoobi.jobid") 不等于 null,则分配此字符串,否则分配字符串 sys.error("Scoobi job id not set.") 返回

回答by senia

It's just a legal character, just like "abcd..."

它只是一个合法的字符,就像“abcd...”

scala> def ?(i: Int) = i > 2
$qmark: (i: Int)Boolean

scala> val a_? = ?(3)
a_?: Boolean = true

UPD:See Valid identifier characters in Scala, Scala method and values names

UPD:请参阅Scala 中的有效标识符字符Scala 方法和值名称

UPD2:In the example "?" could be function, method of thisor just some object with applymethod. It probably returns Option[String].

UPD2:在示例中“?” 可以是函数、方法this或只是一些带有apply方法的对象。它可能会返回Option[String]