Scala Interview Questions | Cloud Data Engineer #ProgrammingTips #adf #scala #java #javaprogramming

preview_player
Показать описание
Q38. Explain the concept of type classes in Scala and their role in providing ad-hoc polymorphism. Provide an example

Unlock Flexible Scala Code! 🚀 Type classes give you ad-hoc polymorphism for extensible designs. See how! #ScalaLang #DevTips #FP #Scala #TypeClasses #Polymorphism #ScalaTips #Development #AdHocPolymorphism

Watch now and learn! #Azure #DataFactory #CloudArchitectAbhiram

Don't forget to like, comment, and subscribe for more Scala interview preparation content! 🔥💡

👉 If you found this video helpful, don’t forget to hit the like button and subscribe for more Spark tutorials!
📢 Have questions or tips of your own? Drop them in the comments below!
Рекомендации по теме
Комментарии
Автор

Code:

// Type class definition for ordering
trait MyOrdering[A] {
def compare(x: A, y: A): Int
}

// Type class instance for ordering integers
implicit object IntOrdering extends MyOrdering[Int] {
def compare(x: Int, y: Int): Int = x - y
}

// Type class instance for ordering strings
implicit object StringOrdering extends MyOrdering[String] {
def compare(x: String, y: String): Int = x.compareTo(y)
}

// Generic function using type class
def findMax[A](list: List[A])(implicit ord: MyOrdering[A]): A = {
list.reduceLeft((x, y) => if (ord.compare(x, y) > 0) x else y)
}

val intList = List(5, 2, 8, 3)
val stringList = List("apple", "orange", "banana")

val maxInt = findMax(intList)
val maxString = findMax(stringList)

println(s"Max integer: $maxInt")
println(s"Max string: $maxString")

CloudMaster_Abhiram
visit shbcf.ru