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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With