Alessandroempire Alessandroempire - 5 months ago 42
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() + "]"


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]


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:


This is identical to writing:


Where the type parameters are explicitly passed.