Alan Coromano
Alan Coromano

Reputation: 26008

What is the syntax to put block of code into getOrElse method?

I want to place a block of a code into getOrElse method, but I can't:

   //1
    getOrElse(() => {
      println("id is not found: " + x.Id)
      new MyClass(-1)
   })

   //2
    getOrElse {
      println("id is not found: " + x.Id)
      new MyClass(-1)
    }

Upvotes: 0

Views: 383

Answers (2)

daaatz
daaatz

Reputation: 394

Probably here You have problems :

new MyClass(-1)

I dont see much code but this problems. See this code which works fine:

import scala.io.Source

class Test(x: Int) {
  override def toString = "In test "+x
}
object Main extends App {

  val test = None
  val b = test.getOrElse({
    println("not found")
    new Test(-1)
  })
  println(b.toString)

}

Upvotes: 0

pedrofurla
pedrofurla

Reputation: 12783

Works fine for me:

scala> None getOrElse { println("AAA")
     | 5 }
AAA
res1: Int = 5

BTW, { () => ... } is a function from the empty argument set to something.

Upvotes: 3

Related Questions