Alessandroempire Alessandroempire - 2 months ago 9
Scala Question

Scala Function syntax

I am currently learning Scala using a tutorial, and I have come across a syntax I do not understand (and I haven not found the answer):

object Demo {
def main(args: Array[String]) {
println(apply(layout, 10))
}

def apply(f: Int => String, v: Int) = f(v)

def layout[A](x: A) = "[" + x.toString() + "]"
}


In

def layout[A](x: A) = "[" + x.toString() + "]"


I do not understand the [A] after layout and before the argument declaration.

Is it the return type?

For me the general syntax for a function in scala is the following;

def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}

Answer

A is something called a type parameter. Type parameters allow you to write a method, generically, for any A. It could be that A is an Int, Double, or even a custom class you've written. Since all of these have a toString method inherited from Any, this will work.

For example, when we do:

println(layout(1L))
println(layout(1f))

This is identical to writing:

println(layout[Long](1L))
println(layout[Float](1f))

Where the type parameters are explicitly passed.