Skip to content

Instantly share code, notes, and snippets.

View nishantv12's full-sized avatar

Nishant Vishwakarma nishantv12

View GitHub Profile
// consider this similar to
// class EmployeeDAO(@Autowired dataSource: EmployeeDataSource)
class EmployeeDAO()(implicit dataSource: EmployeeDataSource) {
def getEmployeeData(): List[Employee] = {
dataSource.fetch()
// data validation
// modification
// ...
}
trait EmployeeDataSource {
def fetch(): List[Employee]
}
class CassandraDataSource extends EmployeeDataSource {
override def fetch(): List[Employee] = ???
}
class FileDataSource extends EmployeeDataSource {
override def fetch(): List[Employee] = ???
object MyComparator {
implicit val compare: MyComparator[Rectangle] = (r1, r2) => r1.breadth.compareTo(r2.breadth)
}
object Sorting8 {
def sort[A : MyComparator](collection: List[A]): List[A] = collection match {
case Nil => Nil
case h :: t => insert(h, sort(t))
}
private def insert[A : MyComparator](elem: A, collection: List[A]): List[A] = {
collection match {
case Nil => List(elem)
case h :: t if MyComparator.compare(elem, h) < 0 => h :: collection
@nishantv12
nishantv12 / MyComparator.scala
Created February 21, 2021 21:57
Helper method to hide the complexity of implicit or implicitly for end user of a type class
object MyComparator {
def compare[T](t1: T, t2:T)(implicit comparator: MyComparator[T]): Int = comparator.compare(t1, t2)
}
object Sorting7 {
def sort[A : MyComparator](collection: List[A]): List[A] = collection match {
case Nil => Nil
case h :: t => insert(h, sort(t))
}
private def insert[A : MyComparator](elem: A, collection: List[A]): List[A] = {
val comparator = implicitly[MyComparator[A]]
collection match {
case Nil => List(elem)
object Sorting6 {
def sort[A](collection: List[A])(implicit comparator: MyComparator[A]): List[A] = collection match {
case Nil => Nil
case h :: t => insert(h, sort(t))
}
private def insert[A](elem: A, collection: List[A])(implicit comparator: MyComparator[A]): List[A] = {
collection match {
case Nil => List(elem)
case h :: t if comparator.compare(elem, h) < 0 => h :: collection
object Sorting5 {
def sort[A](collection: List[A])(comparator: MyComparator[A]): List[A] = collection match {
case Nil => Nil
case h :: t => insert(h, sort(t)(comparator))(comparator)
}
private def insert[A](elem: A, collection: List[A])(comparator: MyComparator[A]): List[A] = {
collection match {
case Nil => List(elem)
case h :: t if comparator.compare(elem, h) < 0 => h :: collection
trait MyComparator[T] {
def compare(t1: T, t2: T): Int
}
// providing the implicit value explicitly when multiple implicit definitions
// are in the same scope
case class Rectangle(length: Int, breadth: Int)
object Rectangle {
implicit val compareByBreadth: (Rectangle, Rectangle) => Int =
(r1, r2) => r1.breadth.compareTo(r2.breadth)
implicit val compareByLength: (Rectangle, Rectangle) => Int =
(r1, r2) => r1.length.compareTo(r2.length)