Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the syntax function[T] means in scala

Tags:

function

scala

I am new to scala and was wondering what the below syntax means?

def exec[T](f: () => T): T = {
  f()
}

As far as my understanding the function "exec" expects function as argument and returns value of type "T" but then what does exec[T] signifies?

like image 932
user1147070 Avatar asked Mar 13 '23 10:03

user1147070


1 Answers

exec is the method name, where T is the generic type parameter for the method.

The method signature needs to specify type T in order for us to be able to specify T as the argument to the method.

When using a generic type parameter, you can pass different types and re-use the same code between them, for example:

scala> exec[Int](() => 1)
res29: Int = 1

scala> exec[Double](() => 1.0)
res30: Double = 1.0

scala> exec[String](() => "hello, world")
res31: String = hello, world

When I declare exec[Int], the parameter f is now a Function0[Int]] (or () => Int if we use syntactic sugar)

As @TzachZohar notes, the Scala compiler is smart enough to be able to infer the type parameter for us at times, which means we can omit the square parenthesis when working with the method. For example:

scala> exec(() => 1)
res32: Int = 1

scala> exec(() => 1.0)
res33: Double = 1.0

scala> exec(() => "hello, world")
res34: String = hello, world

This works as the compiler is able to infer the type of T by the methods return type.

You can read more on these subjects: Type & polymorphism basics, Generic Classes, Local Type Inference and the Scala Specification for Local Type Inference

like image 149
Yuval Itzchakov Avatar answered Mar 15 '23 02:03

Yuval Itzchakov