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

后端 未结 3 1575
夕颜
夕颜 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:51

    If keeping generics, also there is an option to add empty factory - like it's done for Map and Vector. Off course, with such an implementation it will not be a unique instance object for every creation, but when using inc method, it will not produce new objects, it will just reference itself.

    object DataTree {
      def empty[T <% Ordered[T]] = new Tree[T] {
          def contains(num: T):Boolean = false
          def inc(num: T): Tree[T] = {
            new DataTree(num, this, this)
          }
          override def toString = "."
      }
    }
    

    So you can instantiate it as following:

    val t = new DataTree(20, DataTree.empty[Int], DataTree.empty[Int])
    

提交回复
热议问题