Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDevin Tripp
3,826 Pointstransform function does the same thing as stringToInt or intToString
So in this video pasan makes a function called transform that transforms one type to the other. Well, to me it seems a little redundant to do that since the function he creates below this do this without the transform function.
2 Answers
Will Matthews
8,127 PointsIn the example, the transform function is actually only applying a given function "operation" to a given argument "arg". The transform function itself isn't really doing the heavy lifting, that's left to the function that's passed into it.
What this example is meant to highlight is that using generics as we have in the transform function allows us to clearly define a set of rules and type safety without having to be specific about what type or what function will be provided up front. All the transform function does is says, "I'm going to accept two things...a value and a function, and I'm going to spit out a result. However, that function that I'm accepting needs to itself accept an argument that's the same type as the value I've accepted, and will spit out something of the same type that I'll be spitting out."
So the benefit of this is that transform doesn't need to know specifically what types are being passed into it. Because this is just a simplified first step of an example, the real power of these generics may not be obvious yet. But as we get more experienced with these, and use more complex examples, their benefits should become more clear.
Does that make any more sense?
Abdullah Althobetey
18,216 PointsYou are right. I too think the technique shown in the video is useless. Maybe Mr. Pasan shows us this technique merely to understand generics better.
Bankole Abawonse
9,021 PointsBankole Abawonse
9,021 PointsI was of the same opinion as them, but your explanation made things a lot clearer. Thanks a lot!