Parameter extends class

I want to make a class that accepts everything ordered and prints more. (I was just studying, so I know it's a little useless)

class PrinterOfGreater[T extends Ordered](val a:T, val b:T){println(a > b)} 

I know that it cannot be written with this style in scala, but I don’t know how to write it ... Does anyone know?

and why doesn't it compile? Serum line wrapper ordered

 class PrinterOfGreater[T <: Ordered[T]](a:T, b:T){println(a > b)} object A extends Application{new PrinterOfGreater("abc","abd")} 
+4
source share
2 answers

Regarding your second question: String (which in Scala is java.lang.String , at least when targeting the Java / JVM platform) does not define the relational operator > . However, you can easily place this by replacing <: with <% , which indicates the so-called view boundary, which means that in A <% B A there is either a subtype of B , or there is an implicit transformation in the area that will give B when specifying A

This works for String because the Scala standard libraries supply implicit conversion from String to RichString (in Scala 2.7) or to StringOps (in Scala 2.8), where relational operators are defined.

+6
source

Do you want to

 class PrinterOfGreater[T <: Ordered[T]](val a:T, val b:T){println(a > b)} 

<: means "is a subclass" (just like extends does in Java), and the Ordered parameter itself, and you want to clearly indicate that you are trying to compare T , so you specify Ordered[T] .

+4
source

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


All Articles