Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameter extends a class

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")}
like image 288
ryskajakub Avatar asked Mar 19 '10 14:03

ryskajakub


People also ask

Can a method extend a class?

You can use extension methods to extend a class or interface, but not to override them.

What does extending a class in Java mean?

Definition and Usage The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

Can a class extend and interface?

An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

Can we extend and implement in same class?

Note: A class can extend a class and can implement any number of interfaces simultaneously.


1 Answers

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.

like image 148
Randall Schulz Avatar answered Oct 23 '22 23:10

Randall Schulz