what is the purpose A in square brackets in scala

Viewed 5748

I am newly learning Scala. below code has [A] multiple times. Please, someone, explain me in layman terms. I am unable to understand(tried google and read StackOverflow and others answers but I don't get it. The code below is to find kth element from the list.

def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

2 Answers
def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

Here [A] is the type parameter for function findKth. Now what does type parameter mean? Type parameter tells the compiler that method findKth can take parameter of type A. Which is the generic type here because A can be anything. For example A can be Int, Double, another List -- anything.

For more information I would suggest you to go through these links:

https://docs.scala-lang.org/tour/polymorphic-methods.html

https://docs.scala-lang.org/tour/generic-classes.html

It is for declaring generic parameters in Scala, You can call your method with a list of different types (Double, Int, Dogs ... )

If you want to learn more, this post: https://apiumhub.com/tech-blog-barcelona/scala-type-bounds/

For example:

def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

val intList = 1 :: 2::3::4::5::6::7::8::9::10::Nil
val strList = intList.map(_.toString)
println(findKth(9, intList))
println(findKth(3, strList))

As you can see, you can pass to your function a List[Int], or a List[String], it is a way to parametrize functions to accept generics arguments.

You can see it working in here: https://scalafiddle.io/sf/XwaALIk/0

Related