Scala Pattern Compiler Warning

I caused an error in my code that was tougher to find what I would like and what I ideally would like to avoid in the future. I was expecting the Scala compiler to warn me of my error (if I did not miss something).

I reduced it to a trivial case:

Vector.maybeGetVector match { case v:Vector => true case _ => false } case class Vector(x:Int, y:Int) object Vector { def maybeGetVector : Option[Vector] = Some(new Vector(1,2)) } 

The only reason I used wildcard instead of None for failure is because I only want to combine the subtype of the returned Option .

I was expecting a compiler warning, since it’s easy to reason that the first case statement contains unreachable code. Option[Vector] cannot be a subtype of Vector .

The strange part is that if I add the following case statement:

  case i:Int => false 

It throws an error and tells me that Option[Vector] is required.

Is there a way to protect against programmer errors this way, with the exception of naming conventions. The only thing that can compare with Option is Some/None/null . I feel like I'm missing something obvious.

+4
source share
1 answer

If you define your vector class with the final modifier, you will get the error "template type is incompatible with the expected type" that you expect.

I am told that Scala believes that your Option [Vector] may somehow be an instance of the Vector subtype. (This seems impossible to me, but I think the reasoning is at work.) Creating a final vector eliminates that seemingly distant possibility.

So, if the first argument to case should be unavailable, this is not because, as you said, Vector cannot be a subtype of Option [Vector]; but rather because Option [Vector] cannot be an instance of the Vector subtype. Perhaps this is what you had in mind :)

+5
source

All Articles