Learn about currying, a functional programming technique, with a short code example. A lambda function is curried creating three chained functions.
- [Instructor] Currying takes a function, which has multiple arguments, and transforms it into a chain of functions, each of which takes one argument. There will be one function for each argument in the original function. Let's go ahead and add an import. So we're going to say import org, bring in the function library. This time we want the currying, and we're just going to do a star on it.
And down on our function, we're going to create a method called sum3ints, and it is again going to be a lambda, so we're going to say x, which is an Int, y, is an Int, and z, is an Int. And x + y + z. Then we're going to create our function curried.
Now, curried is going to return a function that takes an Int that returns another function that takes an Int, that returns another function that takes an Int, and finally, returns an Int. And the value of that function is going to be sum3ints.curried.
Then we're going to say value of cur equals curried(2)(4)(6), and keep in mind, what we're doing is we're actually making three separate function calls. We're calling the first function with a two, the second function with a four, and the third function with a six. And let's see what the results of that is.
And it's going to equal $cur. And we'll go ahead and run it. And we can see that if we add two plus four, we get six, six and six is 12, and that is the correct answer. It's the same answer we would've got had we called the function with three arguments originally. Take note again of how we called curry. We actually are calling three functions.
Then, we display the results to the terminal.
- Kotlin as a better Java
- Setting up a Kotlin programming environment
- Val vs. var
- Understanding basic Kotlin programming concepts
- Object-oriented programming
- Using Java from Kotlin
- Using Kotlin from Java
- Annotations, reflection, and DSL construction
- Functional programming in Kotlin