score:3

Accepted answer

option trait aka maybe monad is tend to use with functions of type x => option[y]. the for( <- ) yield syntax sugar is replaced by compiler with corresponding flatmap calls which is equivalent for monadic bind operator.

so you are expected to use functions like x => m[y] in flatmap and for-expression with lists\ options\ streams \ iterators etc.

read more here

also your first expression has type list[option[x]]. to extract values properly you could use intermediate value in vladimir's answer.

like

def func1(in: string): option[string] = {
  some(in)
}

def func2(in: string): option[string] = {
  some(in)
}

def func3(in: string): option[string] = {
  some(in)
}


val res = for {
  x <- list(some("hello"), none, some("world"))
  t <- x
  y <- func1(t)
  z <- func2(y)
  w <- func3(z)
} yield w

print(res)

score:0

the error says exactly that - you do not need funcx argument to be option[string]. use just string:

def func1(in: string): option[string] = {
  some(in)
}

def func2(in: string): option[string] = {
  some(in)
}

def func3(in: string): option[string] = {
  some(in)
}


val res = for {
  x <- list(some("hello"), none, some("world"))
  y <- func1(x)
  z <- func2(y)
  w <- func3(z)
} yield w

print(res)

Related Query

More Query from same tag