parameter extends a class
-
21-09-2019 - |
Question
I want to do a class thats accepts anything ordered and prints greater. (I'm just learning so I know it's a bit useless)
class PrinterOfGreater[T extends Ordered](val a:T, val b:T){println(a > b)}
I know that it can't be written by this style in scala, but I don't know how to write it properly... Do anybody know?
and why this doesn't compile? Whey the string wrapper is Ordered
class PrinterOfGreater[T <: Ordered[T]](a:T, b:T){println(a > b)}
object A extends Application{new PrinterOfGreater("abc","abd")}
Solution
Regarding your second question: String
(which in Scala is just java.lang.String
, at least when targeting the Java / JVM platform) does not define the relational operator >
. However, you can accommodate this easily by replacing the <:
with <%
which specifies a so-called view bound, meaning that in A <% B
A
is either a subtype of B
or that there is an implicit conversion in scope that will yield a B
when given an A
.
This works for String
because Scala's standard libraries supply an implicit conversion from String to RichString
(in Scala 2.7) or to StringOps
(in Scala 2.8) where the relational operators are defined.
OTHER TIPS
You want
class PrinterOfGreater[T <: Ordered[T]](val a:T, val b:T){println(a > b)}
<:
means "is a subclass of" (just like extends
does in Java), and Ordered
itself is parameterized, and you want to be clear that you're trying to compare T
, so you specify Ordered[T]
.