2013-07-29 61 views
0

我是新来的Scala和不明白这个代码是这样做的:斯卡拉scopt代码 - 地图getorelse?

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

这是从scopt库found here

理想我想要做的就是把我的代码,做所有的“在这里做些事情“转变成一种方法,那就是做我想做的事情。

然而,当我这样定义,所以我的方法:

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 
    } 
} 

,这样它被称为像这样:

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

我得到的错误:error: class Option takes type parameters def setupVariables(config: Option){

我产生了困惑,因为我不会“得到”parser.parse(args, Config()) map { config => //do stuff here }正在做什么。我可以看到parser.parse返回一个Option,但是在这里做什么是“map”?发生

回答

1

你的错误,因为Option需要一个类型参数,所以你config参数setupVariables应该是一个Option[String]Option[Config]

Option.map采用函数A => B并使用它将Option[A]转换为Option[B]。你可以改变你setupVariables有型Config => Unit和可以做

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

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

创建Option[Unit]

但是,由于您的执行效果只执行setupVariables,因此我建议您通过匹配parser.parse(例如,

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