Possible to make scala require a non-Nothing generic method parameter and return to type-safety

前端 未结 1 2011
日久生厌
日久生厌 2020-12-21 14:40

In scala, the shit can hit the fan if the caller of a generic method omits to explicitly specify the type parameter. For example:

class Expression[+T] // Wil         


        
相关标签:
1条回答
  • 2020-12-21 15:08

    I've found a somewhat hacky solution, but it works. Create a NotNothing type that's contravariant in its type parameter, then provide an implicit object for both Any and Nothing. Now if you try to use a value of NotNothing with Nothing the compiler will complain about ambiguity. Case in point:

    sealed trait NotNothing[-T] 
    
    object NotNothing {
      implicit object YoureSupposedToSupplyAType extends NotNothing[Nothing]
      implicit object notNothing extends NotNothing[Any] 
    }
    

    Then constrain your makey function with the NotNothing type:

    def makey[T : NotNothing]() = { ... }
    

    And voila now you'll get a compile time error if you forget to supply a type!

    0 讨论(0)
提交回复
热议问题