0
0
Kotlinprogramming~5 mins

Infix functions for readable calls in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an infix function in Kotlin?
An infix function is a special kind of function that allows you to call it using infix notation, which means you can write it between its receiver and argument without dots or parentheses, making the code more readable.
Click to reveal answer
beginner
How do you declare an infix function in Kotlin?
You declare an infix function by adding the keyword infix before the function name. It must be a member function or an extension function with a single parameter and no varargs or default values.
Click to reveal answer
intermediate
Example: What does this Kotlin code do?<br>
infix fun Int.times(str: String) = str.repeat(this)
This code defines an infix function times for Int that repeats the given string the number of times equal to the integer. For example, 2 times "Hi" returns "HiHi".
Click to reveal answer
intermediate
What are the requirements for a function to be used as infix in Kotlin?
It must be a member or extension function, have a single parameter, not accept varargs or default parameter values, and be marked with the infix keyword.
Click to reveal answer
beginner
Why use infix functions? Give a real-life analogy.
Infix functions make code look like natural language, improving readability. Like saying "I give you" instead of "I.give(you)", it feels more like a simple conversation.
Click to reveal answer
Which keyword is used to declare an infix function in Kotlin?
Ainfix
Binline
Coverride
Dfun
What is a requirement for the parameter of an infix function?
AIt must be nullable
BIt can have multiple parameters
CIt must be a vararg parameter
DIt must be a single parameter without default values
How would you call an infix function named connect on an object a with argument b?
Aconnect(a, b)
Ba.connect(b)
Ca connect b
Dconnect a b
Can an infix function be a top-level function (not inside a class or object)?
AOnly if marked inline
BNo, it must be a member or extension function
CYes, always
DOnly if it has no parameters
What is the benefit of using infix functions?
AImproves code readability by allowing natural language style calls
BMakes functions run faster
CAllows multiple parameters
DAutomatically handles null safety
Explain what an infix function is and how to declare one in Kotlin.
Think about how you write functions that look like natural language.
You got /4 concepts.
    Describe a simple example of an infix function and how it improves code readability.
    Use a real-life analogy or simple string repetition example.
    You got /4 concepts.