Polymorphism in Scala can be achieved through type parameterization. Let us define class g with attributes x,y as integers as
We can use Type parameter like followsscala> class g(val x:Int, val y:Int) defined class g
scala> class g[T](val x:T, val y:T)
defined class g
scala> val obj=new g[Char]('a','b')
obj: g[Char] = g@a53564
scala> obj.x
res11: Char = a
scala> obj.y
res12: Char = b
We need not specify the type parameter explicitly like that, the Scala compiler can infer the Type from function parameters
Now we can play a bitscala> val obj=new g('a','b') obj: g[Char] = g@a53564 scala> obj.x res3: Char = a
scala> val obj1=new g(1,2) obj1: g[Int] = g@a53564 scala> obj1.y res3: Char = 2
scala> val obj=new g(1,true)
obj: g[AnyVal] = g@11d95
scala> obj.x
res1: AnyVal = 1
scala> obj.y
res2: AnyVal = true
Notice that val obj=new g(1,true) doesn't cause a type mismatch error even Value 1 is of type Int and true is of Boolean while both parameters are expected to be of same type. The reason is that, Boolean, Char, Int etc. are Subtypes of AnyValue.Here The compiler inferred the type as AnyValue looking at the parameters passed.We can also have multiple Type parameters as follows
scala> class g[T,H](val x:T, val y:H)
defined class g
scala> val obj=new g('A',9)
obj: g[Char,Int] = g@14f7121
scala> obj.x
res10: Char = A
scala> obj.y
res11: Int = 9
We can define functions of parameterized type like followsscala> def f[T](x:T):Unit=print(x)
f: [T](T)Unit
scala> f[Int](6)
6
scala> f(6)
6
scala> f("ssss")
ssss
No comments:
Post a Comment