Scala: How do I meet the requirements of type parameters of common classes?

I am creating some parameterized C [T] classes, and I want some characteristics requirements of type T to be a parameter of my class. It would be simple if I just wanted to say that T is inherited from traits or classes (as happens with Ordering). But I want him to implement some functions.

For example, I saw that many predefined types implement MinValue and MaxValue, I would like my type T to implement them too. I got some tips to just define an implicit function. But I would not want all users to be obligated to implement this function for them when it is already implemented. I could implement them in my code too, but it seemed like a very bad decision.

For example, when defining heaps, I would like to allow users to create an empty heap. In these cases, I want to put in place a value with a minimum value that can be of type T. Obviously, this code does not work.

class Heap[T](val value:T,val heaps:List[Heap[T]]){
    def this()=this(T.MinValue,List())
}

I would also like to get some tips on the really good online links of Scala 2.8.

+3
source share
2 answers

A lot of things, all of which are related to each other through the sharing of several methods (albeit with different types of return). Sounds like text polymorphism to me!

roll on a class like ...

class HasMinMax[T] {
  def maxValue: T
  def minValue: T
}

implicit object IntHasMinMax extends HasMinMax[Int] {
  def maxValue = Int.MaxValue
  def minValue = Int.MinValue
}

implicit object DoubleHasMinMax extends HasMinMax[Double] {
  def maxValue = Double.MaxValue
  def minValue = Double.MinValue
}

// etc

class C[T : HasMinMax](param : T) {
  val bounds = implicitly[HasMinMax[T]]
  // now use bounds.minValue or bounds.minValue as required
}

UPDATE

A designation [T : HasMinMax]is context-related and syntactic sugar for:

class C[T](param : T)(implicit bounds: HasMinMax[T]) {
  // now use bounds.minValue or bounds.minValue as required
}
+5
source

:

trait Base

class C[T <: Base]

C T, Base.

:

trait Requirement[T] {
  def requiredFunctionExample(t: T): T
}

class C[T](implicit req: Requirement[T])

, C , Requirement T, . Requirement T , , , , .

+2

Source: https://habr.com/ru/post/1778165/


All Articles