Vangelis Kostas
Vangelis Kostas

Reputation: 93

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

Upvotes: 4

Views: 2214

Answers (2)

mizerlou
mizerlou

Reputation: 186

it's instructive to look at the definition of fold:

def fold[B](ifEmpty: => B)(f: A => B): B

so, when you call

Option("hi").fold(None)(x => Some(x))

the inferred type B is Option[Nothing] because there's no way for the compiler to know what kind of None you meant. in this case, you can help the compiler out by using Option.empty and specifying a type:

Option("hi").fold(Option.empty[String])(x => Some(x))

Upvotes: 1

codejitsu
codejitsu

Reputation: 3182

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)

Upvotes: 4

Related Questions