0

I want to get value from function that passed as parameter and returns Option[Int], after that if I have None throw an exception and in any other case return value I tried to do like this:

def foo[T](f: T => Option[Int]) = {
   def helper(x: T) = f(x)
   val res = helper _
   res match {
       case None => throw new Exception()
       case Some(z) => z
}

I call it like this:

val test = foo[String](myFunction(_))
test("Some string")

I have compilation error with mismatched types in match section (Some[A] passed - [T] => Option[Int] required) As I understood res variable is reference to the function and I cannot match it with optional either call get\gerOrElse methods. Moreover I probably just dont get how the underscore works and doing something really wrong, I'm using it here to pass a something as parameter to function f, can you explain me where I made a mistake?

Pot001
  • 3
  • 2

1 Answers1

2

helper is a method taking a T and returning an Option[Int].

res is a function T => Option[Int].

Difference between method and function in Scala

You can't match a function T => Option[Int] with None or Some(z).

You should have an Option[Int] (for example the function applied to some T) to make such matching.

Probably you would like to have

  def foo[T](f: T => Option[Int]) = {
    def helper(x: T) = f(x)
    val res = helper _
    (t: T) => res(t) match {
      case None => throw new Exception()
      case Some(z) => z
    }
  }

or just

  def foo[T](f: T => Option[Int]): T => Int = {
    t => f(t) match {
      case None => throw new Exception()
      case Some(z) => z
    }
  }

or

  def foo[T](f: T => Option[Int]): T => Int = 
    t => f(t).getOrElse(throw new Exception())
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66