scalapattern-matchingtype-bounds

In Java or Scala, how to define conditional control flow based on whether type bound is satisfied?


In scala, I have a class definition:

class A[T >: Null]{}

And a function that optionally creates an instance:

def use[T](): Option[A[T]]

now I want to define it such that:

How to write function use in this case?


Solution

  • This is approach with a type class

    def use[T]()(implicit sel: Selector[T]): sel.Out = sel.x
    
    trait Selector[T] {
      type Out
      val x: Out
    }
    
    trait LowPrioritySelector {
      implicit def default[T]: Selector[T] { type Out = None.type } = new Selector[T] {
        override type Out = None.type
        override val x: Out = None
      }
    }
    
    object Selector extends LowPrioritySelector {
      implicit def superTypeOfNull[T >: Null]: Selector[T] { type Out = Some[A[T]] } = new Selector[T] {
        override type Out = Some[A[T]]
        override val x: Out = Some(new A[T])
      }
    }
    
    use[String]() // Some(App$A@34340fab)   
    use[Int]() // None