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:
T >: Null
is not satisfiedHow to write function use
in this case?
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