为什么我在Scala中得到Some而不是String

Far*_*mor 4 scala

为什么我得到[Some] Object而不是[String]对象?
Some对象在方法调用中不能用作String参数.

config def回报String,所以我期望类型为String.
但是当我输入"你好"时,Scala得到它是正确的.

    def config(s: String) = Play.current.configuration.getString(s).toString()
    Logger.info(config("recaptcha.publicKey"))
    Logger.info("Hello")
Run Code Online (Sandbox Code Playgroud)

产量

[info] application - Some(6LeDMdASAAAAAC4CFIDY-5M7NEZ_WnO0NO9CSdtj)
[info] application - Hello
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 11

你是不必要的调用toString()Option[String](它Play.current.configuration.getString()返回),试试这个:

def config(s: String) = Play.current.configuration.getString(s).get
Run Code Online (Sandbox Code Playgroud)

要么 也许 优选:

Play.current.configuration.getString(s).getOrElse("some default")
Run Code Online (Sandbox Code Playgroud)

  • @Farmor足够公平,但如果你真的希望它抛出一个异常,你仍然不应该使用`get`:使用`getOrElse(sys.error("Illegal config String"))`来分离关注点,澄清错误信息,并明确表示您实际上在这里进行有效性检查. (2认同)

Tal*_*man 8

getString返回一个Option [String],这样当没有任何内容可以返回时它可以返回一个空值.当有东西要返回时,它返回Some(字符串),你可以使用get()方法获取内部字符串.