4. Type Classes
Type Classes are Introduce first in haskell language
Scala Type Classes are Pattern instead of language feature
Example:
scala.math.Numaric, scala.math.Ordering
Every Thing in Scalaz is Type class ( monoids, monads,
applicative , functors )
5. OverLoading
case class Book(title:String,author:String)
case class Movie(title:String,director:String)
object OverLoading {
def serialize(book:Book)= "Book("
+book.title+","+book.author+")"
def serialize(movie:Movie)= "Book("
+movie.title+","+movie.director+")"
}
6. OverLoading
case class Book(title:String,author:String)
case class Movie(title:String,director:String)
object OverLoading {
def serialize(book:Book)= "Book("
+book.title+","+book.author+")"
def serialize(movie:Movie)= "Book("
+movie.title+","+movie.director+")"
}
8. Problem With Interface
We Have Coupling Problem Here , How each class
is serialize , this information has to be in the class.
In order to add more trait and override the methods
I need to have control on these classes. I should be
allowed to view and modify the source code.
9. Pattern Matching
object Serialize {
def serialize(x:Any)
{
x match {
case b:Book => "Book(" +b.title+","+b.author+")"
case m:Movie => "Movie(" +m.title+","+m.director+")"
}
}
}
10. Problem With Pattern Matching
● Both the Movie and Book classes are unaware how
actually there serialized.
● If I need more than one type of serialization than I need
more serialize method with it's own case match block.
● Now we have fixed the coupling problem, but
unfortunatly we have introduce new coupling
● Method serialize need to know about all the classes
which need to be serialize.
● Problem of control and source code is still exist
11. Type Class
case class Book(title:String,author:String)
case class Movie(title:String,director:String)
trait Serializable[T] {
def ser(t:T):String
}
object Serializable{
def serialize[T](t:T, s:Serializable[T])=s.ser(t)
}
object BookIsSerialzabel extends Serializable[Book]
{
def ser(book:Book)= "Book(" +book.title+","+book.author+")"
}
object MovieIsSerialzabel extends Serializable[Movie]
{
def ser(movie:Movie)= "Movie(" +movie.title+","+movie.director+")"
}
12. Type Class With Implicit
case class Book(author:String) extends Card[Book]
case class Movie(director:String) extends Card[Movie]
trait Serializable[T] {
def ser(t:T):String=t.asInstanceOf[Card[T]].title
}
object Serializable{
def serialize[T](t:T)(implicit s:Serializable[T])=s.ser(t)
implicit object BookIsSerialzabel extends Serializable[Book]
{override def ser(book:Book)= "Book(" +book.title+","+book.author+")"}
implicit object MovieIsSerialzabel extends Serializable[Movie]
{ override def ser(movie:Movie)= "Movie("
+movie.title+","+movie.director+")"}
}