bharal
bharal

Reputation: 16204

Scala scopt code - map getorelse?

i am new to scala and do not understand what this code is doing:

parser.parse(args, Config()) map {
  config =>
    //do stuff here
} getOrElse {
  //handle stuff here
}

This is from the scopt library found here

Ideally what i want to do is put my code that does all the "do stuff here" into a method that, well, does what I want it to do.

However, when i define my method like so:

def setupVariables(config: Option){
    host = config.host
    port = config.port
    delay = config.delay
    outFile = config.outFile

    if (!(new File(config.inputFile)).exists()) {
      throw new FileNotFoundException("file not found - does the file exist?")
    } else {
      inputFile = config.inputFile
    }
}

so that it is called like so:

parser.parse(args, Config()) map {
  config =>
    setupVariables(config)
} getOrElse {
  //handle stuff here
}

I get the error: error: class Option takes type parameters def setupVariables(config: Option){

My confusion arises because i don't "get" what parser.parse(args, Config()) map { config => //do stuff here } is doing. I can see that parser.parse returns an Option, but what is "map" doing here?

Upvotes: 0

Views: 363

Answers (1)

Lee
Lee

Reputation: 144206

You error occurs because Option requires a type parameter, so your config argument to setupVariables should be an Option[String] or an Option[Config].

Option.map takes a function A => B and uses it to transform an Option[A] into an Option[B]. You could change your setupVariables to have type Config => Unit and could do

def setupVariables(config: Config) {
    ...
}

parser.parse(args, Config()).map(setupVariables)

to create an Option[Unit].

However, since you are only executing setupVariables for its effects, I would suggest being more explicit by matching on the result of parser.parse e.g.

parser.parse(args, Config()) match {
    case Some(cfg): setupVariables(cfg)
    case _ => //parse failed
}

Upvotes: 1

Related Questions