Tuesday, July 21, 2020

Scala : Generic Types in Scala


Generic Types in Scala

a) def func1[T](a : T) : T = a

Explanation :

def listOfDuplicates[A](x: A, length: Int): List[A] = {
  if (length < 1)
    Nil
  else
    x :: listOfDuplicates(x, length - 1)
}

println(listOfDuplicates[Int](3, 4))  // List(3, 3, 3, 3)----1
println(listOfDuplicates("La", 8))  // List(La, La, La, La, La, La, La, La)---2

we explicitly provide the type parameter by writing [Int]. Therefore the first argument must be an Int and the return type will be List[Int].
You don’t always need to explicitly provide the type parameter. The compiler can often infer it based on context or on the types of the value arguments. In this example, "La" is a String so the compiler knows A must be String.


b) 

class Stack[A] {

  private var elements: List[A] = Nil
  def push(x: A) { elements = x :: elements }
  def peek: A = elements.head
  }
}

Explanation:

This implementation of a Stack class takes any type A as a parameter. 
This means the underlying list, var elements: List[A] = Nil, can only store elements of type A. 
The procedure def push only accepts objects of type A (note: elements = x :: elements prepending x to the current elements).
Nil here is an empty List and is not to be confused with null.

example 1:

val stack = new Stack[Int]
stack.push(1)
stack.push(2)
println(stack.peek)  // prints 2

example 2:

class Fruit
class Apple extends Fruit
class Banana extends Fruit

val stack = new Stack[Fruit]
val apple = new Apple
val banana = new Banana

stack.push(apple)
stack.push(banana)

No comments:

Post a Comment