How to create object/singleton of generic type in Scala?

后端 未结 3 1524
夕颜
夕颜 2021-02-10 23:42

In the code shown below, how can I convert EmptyTree to object (Singleton) ?

trait Tree[T] {
    def contains(num: T): Boolean
    def inc( num: T )         


        
3条回答
  •  终归单人心
    2021-02-10 23:45

    You have to fix the generic argument because that's the only time you can provide it:

    scala> trait A[T]
    defined trait A
    
    scala> object B extends A[Int]
    defined object B
    

    Obviously you want to reuse EmptyTree for all types of T, so instead of defining A[SOMETYPE] for each type just use bottom type Nothing:

    scala> object B extends A[Nothing]
    defined object B
    

    This object can be used with any tree.

    That's exactly how Option[T] is implemented in Scala. Here is how None is defined:

    case object None extends Option[Nothing]
    

提交回复
热议问题