0
0
Kotlinprogramming~10 mins

Single-expression functions in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a single-expression function that returns the square of a number.

Kotlin
fun square(x: Int): Int = [1]
Drag options to blanks, or click blank then click option'
Ax * x
Breturn x * x
Cx + x
Dprintln(x)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' keyword inside a single-expression function.
Using curly braces instead of '=' for single-expression functions.
2fill in blank
medium

Complete the code to define a single-expression function that returns the length of a string.

Kotlin
fun lengthOf(str: String): Int = [1]
Drag options to blanks, or click blank then click option'
Astr.length()
Bstr.length
Cstr.size
Dstr.count()
Attempts:
3 left
💡 Hint
Common Mistakes
Using length() with parentheses which is invalid in Kotlin.
Using size which is for collections, not strings.
3fill in blank
hard

Fix the error in the single-expression function that returns true if a number is even.

Kotlin
fun isEven(num: Int): Boolean = num [1] 2 == 0
Drag options to blanks, or click blank then click option'
A%
B/
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using division / instead of modulo %.
Using multiplication or addition operators which don't check evenness.
4fill in blank
hard

Complete the code to create a single-expression function that returns the last character of a string.

Kotlin
fun lastChar(str: String): Char = str[1]
Drag options to blanks, or click blank then click option'
A[
B]
Cstr.length - 1
DlastIndex
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets for indexing.
Omitting the str. prefix before length.
5fill in blank
hard

Fill all three blanks to define a single-expression function that returns a greeting message with the user's name.

Kotlin
fun greet(name: String): String = "Hello, [1]!".[2]() + [3]
Drag options to blanks, or click blank then click option'
A$name
Buppercase
C" Have a nice day."
DtoUpperCase
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase() which is Kotlin 1.5+ but not always available.
Forgetting to add parentheses after the uppercase function.
Not adding the extra greeting string at the end.