Back to Home
What Is a Function in Scala

What Is a Function in Scala

B
Blizine Admin
·2 min read·0 views

Daniel Toni Posted on May 31 What Is a Function in Scala # scala # functional One of the most important concept in Scala and Functional Programming, is that functions are first-class values. This means functions are treated as any other data type in the language: they can be assigned to variables, passed as arguments to other functions, and returned from functions. Treating functions as first-class values enables powerful code design capabilities, such as: Higher-Order Functions Function Composition Closures and Currying The way Scala achieves this feature is by treating functions as objects, instances of a class, just like String , Int or any other type. A function is an object with one method. First, let's look at the long way of building a function value. We can define a generic trait called MyFunction that takes a parameter of type A and returns a value of type B . This trait will expose an apply method: trait MyFunction [ A , B ] { def apply ( arg : A ) : B } Enter fullscreen mode Exit fullscreen mode We can then create a variable and instantiate an anonymous class using this trait: val doubler = new MyFunction [ Int , Int ] { override def apply ( arg : Int ) : Int = arg * 2 } val randomNumber : Int = 14 doubler . apply ( randomNumber ) // 28 Enter fullscreen mode Exit fullscreen mode Notice how doubler is an object with an apply method. The Scala compiler provides syntactic sugar that allows us to omit the explicit .apply invocation, resulting in doubler(randomNumber) . This matches the exact syntax we use to call methods, making every function value look and feel callable. Fortunately, we don't need to define these traits ourselves. The Scala standard library provides built-in traits named FunctionX , such as Function1[A, B] and Function2[A, B, C] . The number in the trait name represents how many parameters the function accepts. Thus, our custom MyFunction[A, B] is functionally equivalent to Function1[A, B] (though the standard library traits bundle addition

📰Dev.to — dev.to

Comments