Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Scala
Posted by: Pahay Ragh
Added: Oct 25, 2020 3:27 AM
Views: 8
Tags: no tags
  1. //    “Pimp my library” (implicit classes)
  2.  
  3.     case class StrOps(str:String) {
  4.       def plainText = str.toUpperCase() + " is Normal Text"
  5.       def isQuestion:String = {
  6.         if (str.endsWith("?")) s"$str is a Question"
  7.         else plainText
  8.       }
  9.     }
  10.  
  11.     implicit def string2StringOps(str:String):StrOps = StrOps(str)
  12.  
  13.     println("Hello World".plainText) // HELLO WORLD is Normal Text
  14.     println("Hello World ?".isQuestion) //This Hello World ? is a Question
  15.     println("Hello World !".isQuestion) // HELLO WORLD ! is Normal Text
  16.  
  17.     //Implicit Ordering
  18.  
  19.     case class SalesClass(product:String, unitPrice:Double, qty:Int){
  20.       def totalPrice :Double = unitPrice * qty
  21.     }
  22.  
  23.  
  24.  
  25.     object ProductSorting {
  26.       // Note that because `Ordering[A]` is not contravariant, the declaration
  27.       // must be type-parametrized in the event that you want the implicit
  28.       // ordering to apply to subclasses of `SalesClass`.
  29.       implicit def classStringSorting[A <:SalesClass]: Ordering[A] = {
  30.         Ordering.fromLessThan((a, b) => a.product.compareTo(b.product) < 0)
  31.       }
  32.     }
  33.  
  34.     object TotalSort {
  35.       implicit def totalPriceOrdering: Ordering[SalesClass] = {
  36.         Ordering.fromLessThan((a, b) => a.totalPrice < b.totalPrice)
  37.       }
  38.     }
  39.  
  40.     val sales:List[SalesClass]= List(
  41.       SalesClass("Pear",2.5,10),
  42.       SalesClass("Banana",0.5,10),
  43.       SalesClass("Apple",1.5,10)
  44.     )
  45.  
  46.  
  47.     println(sales)
  48.     sales.foreach(record => println(record.totalPrice)) // 5.0 15.0 , 25.0
  49.  
  50.     import ProductSorting._
  51.     println(sales.sorted) // List(SalesClass(Apple,1.5,10), SalesClass(Banana,0.5,10), SalesClass(Pear,2.5,10))
  52.  
  53.  
  54.     import TotalSort._
  55.     println(sales.sorted)
  56.