如果我在getOrElse中使用print语句,则无法在Option的getOrElse路径中分配值

时间:2019-06-03 06:45:56

标签: scala

我想从application.conf中读取一个值。如果该值不存在,我想分配一个默认值

val keyspaceOption:Option[String] = configuration.getOptional("db.keyspaceName")
  println(s"database will connect with keyspace ${keyspaceOption}")
  val keyspaceName = keyspaceOption.map(keyspace =>{
   keyspace
  })
    .getOrElse(
      println("unable to pick keyspace name from configuration. Using default value")
      "someDefaultName"
    )
  cassandraConnectionService.initKeySpace(cassandraSession,keyspaceName)

我在上面的代码中遇到以下错误

Error:(171, 7) ')' expected but string literal found.
      "someDefaultName"

如果我在getOrElse中删除了打印语句,则它将编译。为什么?

.getOrElse(//works
      //println("unable to pick keyspace name from configuration. Using default value")
      "someDefaultName"
    )

1 个答案:

答案 0 :(得分:1)

您需要替换

.getOrElse(
  println("unable to pick keyspace name from configuration. Using default value")
  "someDefaultName"
)

使用

 .getOrElse{
      println("unable to pick keyspace name from configuration. Using default value");
      "someDefaultName"
 }