【问题标题】:Struggling with Play.current.configuration.getStringList("mongodb.replicaSetSeeds") Option handling挣扎于 Play.current.configuration.getStringList("mongodb.replicaSetSeeds") 选项处理
【发布时间】:2013-06-20 23:30:09
【问题描述】:

我有一个类似的 conf/application.conf 设置

mongodb.replicaSetSeeds = ["bobk-mbp.local:27017","bobk-mbp.local:27018"]

我在我的代码中提取它(实际提取有点不同,但这是它的要点)

val replicaSetSeeds = Play.current.configuration.getStringList("mongodb.replicaSetSeeds")
val listOfString: List[String] = replicaSetSeeds.getOrElse(List("localhost"))

但是编译器讨厌我

type mismatch;  found   : Object  required: List[String]

getStringList 的签名是

def getStringList(path: String): Option[java.util.List[String]]

我该如何处理这里的 None 情况还是我的问题 List[String] 与 List[java.util.String] 不同?

【问题讨论】:

    标签: scala playframework playframework-2.1 playframework-2.5


    【解决方案1】:

    试一试:

    import collection.JavaConversions._
    val optList:Option[List[String]] = Play.current.configuration.getStringList("mongodb.replicaSetSeeds").map(_.toList)
    val list = optList.getOrElse(List("localhost"))
    

    这里发生了很多事情。首先,您需要导入 JavaConversions 隐式,因为返回的是 Option[java.util.List[String]],而我们希望它是 scala List。通过执行map(_.toList),我强制隐式转换启动并给我一个Option[List[String]],然后事情就很简单了。

    【讨论】:

      【解决方案2】:

      在play 2.5中,你需要使用依赖注入,以下对我来说效果很好:

      1) 在你的课堂上注入Configuration

      class Application @Inject()(
        configuration: play.api.Configuration
      ) ...
      

      2) 在你的方法中

      import scala.collection.JavaConversions._
      val optlist = configuration.getStringList("mongodb.replicaSetSeeds").map{_.toList}
      val list = optList.getOrElse(List("localhost"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 2014-08-30
        • 1970-01-01
        • 2014-04-05
        • 2015-08-24
        • 2021-08-05
        • 2012-01-06
        相关资源
        最近更新 更多