Sergey Alaev
Sergey Alaev

Reputation: 3972

Simpler way to max() two Ordered objects

Given two Ordered vals, I can find maximum using following code:

abstract class C extends Ordered[C] ()

val v1: C = ???
val v2: C = ???

val max = implicitly[Ordering[C]].max(v1, v2)

Can it be done simpler?

Upvotes: 3

Views: 904

Answers (3)

Didier Dupont
Didier Dupont

Reputation: 29528

If you import Ordering._, you get v1 max v2 (or v1.max(v2), as you might prefer). Also v1 < v2, etc

Upvotes: 3

Vered Rosen
Vered Rosen

Reputation: 381

Not sure it is much simpler (and it may actually suit better when you have more than 2 elements that you want to find their max) but you can do:

val max = List(v1, v2).max

as that max method on collection takes an implicit Ordering

Upvotes: 1

Related Questions