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

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

    Let me detalize Alexey's answer. Here is full implementation with some code style improvements:

    First define your trait with aknowledgment of its covariance:

     trait Tree[+T] {
        def contains[U >: T : Ordering](num: U): Boolean
    
        def inc[U >: T : Ordering](num: U): Tree[U]
      }
    

    Next define your subtype-of-all-trees object

      case object EmptyTree extends Tree[Nothing] {
        def contains[U >: Nothing : Ordering](num: U): Boolean = false
        def inc[U >: Nothing : Ordering](num: U): Tree[U] =
          DataTree(num, EmptyTree, EmptyTree)
        override def toString = "."
      }
    

    Now change your general case implementation:

      case class DataTree[T: Ordering](x: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
        import Ordering.Implicits._
        def contains[U >: T : Ordering](num: U): Boolean = 
          if (num < x) left.contains(x)
          else if (num > x) right.contains(x)
          else true
    
        def inc[U >: T : Ordering](num: U): Tree[U] = 
          if (num < x) DataTree(x, left.inc(num), right)
          else if (num > x) DataTree(x, left, right.inc(num))
          else this
    
        override def toString = "{" + left + x + right + "}"
      }
    

    You could be a little bit frustrated since I replaced your Ordered with Ordering, but you should know that view bounds are deprecated

提交回复
热议问题