19

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

And here's one example

 def getJobId(conf: Configuration): String =
    ?(conf.get("scoobi.jobid")).getOrElse(sys.error("Scoobi job id not set."))
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • Can you give an example? The "?" could be part of a method name, class name, or something else. It's not a standard operator in Scala. – Jesper Apr 06 '12 at 06:58
  • `val lovely_? = isItAGoodDay()` <-- like that? –  Apr 06 '12 at 07:01
  • is it just me or is the "?" helper method in this case utterly pointless? The same result, with fewer characters and, IMHO, more clarity, is obtained with standard, conf.get("foo") getOrElse sys.error("bar") – virtualeyes Apr 06 '12 at 09:42
  • 1
    @virtualeyes `Option.apply(x)` converts `null` to `None`. So If `conf.get("foo")` doesn't return an `Option`, but might return `null`, then this is done to convert the possible `null` to `None` (see Christian's answer). – Jesper Apr 06 '12 at 11:14
  • 1
    Assumed the get in this case was on an Option, but looking again, not the case. "import Option.{apply => ?}" is, btw, really quite awesome ;-) – virtualeyes Apr 06 '12 at 18:41

2 Answers2

31

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

import Option.{apply => ?}

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

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

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

Christian
  • 4,543
  • 1
  • 22
  • 31
8

It's just a legal character, just like "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

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

Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129