Replacing case class inheritance with extractors preserving exhaustiveness checks in Scala

后端 未结 3 1372
说谎
说谎 2021-01-04 23:39

I have a simple class hierarchy that represents a graph-like structure with several distinct types of vertexes implemented using case classes:

sealed trait N         


        
3条回答
  •  难免孤独
    2021-01-05 00:03

    In general, this can't be done.

    Sealed classes are a special case (no pun intended) because scalac knows at compile time how many matches are possible.

    But since extractors allow you to run arbitrary code and because of the damnable halting problem, there's no way for the compiler to guarantee in every case that you'll check every case. Consider:

    def test(foo: Int) {
      foo match {
        case IsMultipleOf8(n) => printf("%d was odd\n", n)
      }
    }
    

    This is not exhaustive because it doesn't handle numbers that aren't multiples of 8, but the compiler cannot deduce (without running your extractor on all Int's) that only some values of type Int are multiples of 8.

提交回复
热议问题