Search code examples
scalafold

Scala fold on Option return type


I am very new to Scala and i would like to return a Some[String] or a None after doing some loging but it seems the types returned are not consistent for the fold to work.

(Option[String]).fold{
            logger.info("Message append failed")
            None
          }{stuff=>
            logger.info("Message appended")
            Some(stuff)
          }

The returned compiler error is the following Expression of type Some[String] does not conform to expected type None.type


Solution

  • I think, you use the wrong type signature. You have to call the fold method on some Option instance. For example:

    scala> val opt = Option("test")
    scala> opt.fold[Option[String]] {
         | println("Message append failed.")
         | None
         | } { stuff =>
         | println("Message appended!")
         | Some(stuff)
         | }
    Message appended!
    res3: Option[String] = Some(test)