Two questions
Questions 1 What is the use of a class which takes type parameter
I could understand the usefulness of
trait SomeTrait[T] I am struggling to comprehend what could be a use case of something like
class SomeClass[A](a:A) {...} When we pass a parameter of a known type to a function or a class, we know which operations are allowed on that parameter. So if I have a class as follows, I know that as the parameter is of type Int, I can perform '+' on the parameter 'a'
scala> class IntTest(a:Int) { | def plusandPrintInt = {println(a+1)} //as 'a' is Int, we can do + | } defined class IntTest scala> val i = new IntTest(1).plusandPrintInt 2 i: Unit = () But when I create a class which accepts type parameter [A], then the parameter could be of any type. Thus I do not what operations can be done on the passed parameter
scala> class TypeClass [A](a:A) { | // what possibly can be done on A without knowing what A is? | } defined class TypeClass Traits are different because we do not implement functions in trait but let other class do so. When a Trait which accepts Type parameter is extended, it is generally extended by specifying the real parameter type. Thus we can call specific operations on parameters as we know what the type of parameters are
scala> trait TraitClass [T] { | def whatever (t:T) // I am not bothered as I do not need to implement this function | } defined trait TraitClass scala> class extendTraitClass extends TraitClass[Int] { | def whatever(t:Int) {println(t+1)} //I know that t is Int so I can use + | } defined class extendTraitClass scala> (new extendTraitClass).whatever(1) 2 It seems the only operations available to 'a' are follows
scala> def someFunction[A](a:A) { | a. //double tabbed to get this list != + == ensuring formatted hashCode toString ## -> asInstanceOf equals getClass isInstanceOf ? Question 2 Is type class same as type trait?