Alan Coromano
Alan Coromano

Reputation: 26008

Type mismatch at match ... case

Here is a simplified version of code I have:

class MyClass(a: Int)

def method1: Option[List[MyClass]] = {
  val response = getData

  val res = response match {
    case Left(_)
         | Right(Class1(None))
         | Right(Class1(Some(Class2(_, _, Nil)))) => None
    case Right(Class1(Some(Class2(_, _, xs: Seq[Class3])))) => xs map { x => new MyClass(x.someVal) }
  }

  Some(res)
}

It complains

found   : Equals
[error]  required: List[MyClass]
[error]    Some(res)

How do I fix it?

Upvotes: 1

Views: 470

Answers (2)

4lex1v
4lex1v

Reputation: 21557

As an alternative solution you can wrap the second case into Option or Some:

 val res = response match {
    case Left(_)
         | Right(Class1(None))
         | Right(Class1(Some(Class2(_, _, Nil)))) => None
    case Right(Class1(Some(Class2(_, _, xs: Seq[Class3])))) => Option(xs map { x => new MyClass(x.someVal)) }
  }

and remove Some(res) at the end

Upvotes: 1

senia
senia

Reputation: 38045

You should replace None with Nil in the first case.

Common type of Option and List is Equals, so the result of x match { case ... => None case ... => List() } is Equals, not List.

You should also call toList after map in the second case, otherwise you'll get Seq, not List.

Upvotes: 4

Related Questions