Leave a rating/review
To really master functions, I’ve prepared two challanges for you!
In the first one, you have to create a function which takes in two parameters, the first and last name. Then it has to return the length of the full name.
Leave the last name as an empty String by default, as some people don’t have one!
In the second challenge, you have to overload the initial function, to accept a middle name, because some people have one!
Then use those two functions to print out the lengths of two names.
Remember to use named arguments when needed, when calling functions.
That’s it! :]
Now pause the video, and try to solve the challenges. Then once you’re done, hit the play button to checkout my solution!
Challenge 1:
Create a function which takes in two parameters - a name and a last name.
Because not everyone has a last name,
leave the lastName parameter to be an empty String if it is not passed in.
Then return the length of the person's full name is.
Challenge 2:
Overload the function from the first challenge, by adding a list of Strings parameter, for middle names,
in case someone has one or more middle names.
Use the function to return the full name length, for a name with and without middle names.
Remember to use named arguments if needed.
Start off by declaring the function as follows:
fun getFullNameLength(name: String, lastName: String = "") =
name.length + lastName.length
This function is pretty simple, it sums the length of these two strings.
Then print out the name length by calling the function like so:
val nameLength = getFullNameLength("Ayo", "Balogun")
println(nameLength)
Run the project, and you should see the length!
–
Now for the second challenge, overload the function, to add a middle name parameter like so:
fun getFullNameLength(
name: String,
middleName: String = "",
lastName: String = "",
): Int {
return name.length + middleName.length + lastName.length
}
Finally, print out the length of a name with the middle name:
val length = getFullNameLength("Damini", "Ebunoluwa", "Ogulu")
println(length)
Run the project, and you should see the length of their full name!
And that’s quite a long name!