Created
October 25, 2020 03:26
-
-
Save rupeshtr78/f535eb8c8790acabc825e4ca0e631360 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Implicit Ordering | |
case class SalesClass(product:String, unitPrice:Double, qty:Int){ | |
def totalPrice :Double = unitPrice * qty | |
} | |
object ProductSorting { | |
// Note that because `Ordering[A]` is not contravariant, the declaration | |
// must be type-parametrized in the event that you want the implicit | |
// ordering to apply to subclasses of `SalesClass`. | |
implicit def classStringSorting[A <:SalesClass]: Ordering[A] = { | |
Ordering.fromLessThan((a, b) => a.product.compareTo(b.product) < 0) | |
} | |
} | |
object TotalSort { | |
implicit def totalPriceOrdering: Ordering[SalesClass] = { | |
Ordering.fromLessThan((a, b) => a.totalPrice < b.totalPrice) | |
} | |
} | |
val sales:List[SalesClass]= List( | |
SalesClass("Pear",2.5,10), | |
SalesClass("Banana",0.5,10), | |
SalesClass("Apple",1.5,10) | |
) | |
println(sales) | |
sales.foreach(record => println(record.totalPrice)) // 5.0 15.0 , 25.0 | |
import ProductSorting._ | |
println(sales.sorted) // List(SalesClass(Apple,1.5,10), SalesClass(Banana,0.5,10), SalesClass(Pear,2.5,10)) | |
import TotalSort._ | |
println(sales.sorted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment