2012-03-27 26 views
2

我試圖在Scala scopt 2.0.1庫中使用新的不可變的OptionParser。由於OptionParser需要一個泛型類型和幫助方法已經定義了返回Unit一個動作,我得到一個編譯時錯誤:在不可變的SCOPT(Scala)OptionParser(2.0.1)中使用「help」方法

case class Config(directory: String = null) 

val parser = new OptionParser[Config]() { 
    def options = Seq(
    opt("d", "directory", "directory containing the files to be processed") { 
     (value: String, config: Config) => config.copy(directory = value) 
    }, 
    help("?", "help", "Show a usage message and exit")) 
} 

error: type mismatch; 
[INFO] found : scopt.generic.FlagOptionDefinition[Nothing] 
[INFO] required: scopt.generic.OptionDefinition[Config] 
[INFO] Note: Nothing <: Config, but class OptionDefinition is invariant in type C. 

我怎麼能包括「幫助」選項?

回答

2

首先,庫中似乎存在一個錯誤,其中opt的一個重載方法採用了它不應該使用的類型參數C - 至少從我所知道的情況來看。它應該只是從課上拿到C。無論如何,雖然你使用這個調用,但我猜Scala仍然正確地推斷出這個C與該類的CConfig)是一樣的。

問題似乎是help完全沒用 - 它給你FlagOptionDefinition[Nothing],因爲它的action: => C執行是{this.showUsage; exit}

我認爲OptionParser類需要固定...

你可以寫你自己的help方法強制執行C類型參數:

def help2(shortopt: String, longopt: String, description: String) = 
    new FlagOptionDefinition[C](Some(shortopt), longopt, description, 
    { this.showUsage; exit }) 
相關問題