Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Closures2:36 with andi mitre
In Scala you can define a function inside another function or method and then access any variables in the enclosing scope. In this video we’ll learn about closures and how to implement them.
A closure is a function whose return value depends upon a variable 0:00 declared out the function scope. 0:04 Basically with closures, means a variable and 0:07 a function where the variable is no longer in scope. 0:10 Let's dive in and create a closure. 0:13 Let's create a function called a reverse it which will take a string argument 0:16 consisting of our superhero name and a prefix. 0:20 Then it will concatenate the two and reverse the result. 0:23 Let's dive back into the code editor and clean up some of our earlier code. 0:27 So far, we've created a prefix variable which is not a vowel because we'll need to 0:56 change this later in the reverse hit function. 1:01 Let's see how we can use these two, to really show how powerful closures can be. 1:05 In this case, we call the function reverse it by passing the value Thor. 1:17 Let's also check out another example. 1:22 Let's change prefix to "Super Fast." 1:25 In the second example, we call reverseIt, passing it "Wonder Woman." And 1:41 also we've changed the prefix to super fast. 1:45 But what happens when we print out Thor and or when we print out Wonder Woman? 1:49 Let's compile and check out the results. 1:59 Although it's a bit difficult to read, 2:04 we notice that that first prefix is set to lightning. 2:06 And the reverse it function uses the variable prefix which is not in scope. 2:10 We update the variable prefix to super fast. 2:15 However, calling Thor retains the correct instance of prefix. 2:18 I hope you enjoyed exploring Scala with me. 2:23 We've gone through quite a few concepts through out the stages. 2:26 And learned quite a bit about Scala. 2:29 Checkout the teachers notes for more resources and how to proceed from here. 2:31
You need to sign up for Treehouse in order to download course files.Sign up