0
0
Kotlinprogramming~10 mins

Apply function behavior and use cases 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 use the apply function to initialize the object.

Kotlin
val person = Person().[1] {
    name = "Alice"
    age = 30
}
Drag options to blanks, or click blank then click option'
Aapply
Balso
Crun
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' instead of 'apply' which returns the last expression, not the object.
Using 'run' which returns the lambda result, not the object.
Using 'also' which uses 'it' as context, not 'this'.
2fill in blank
medium

Complete the code to print the object's properties using apply.

Kotlin
val car = Car().[1] {
    brand = "Toyota"
    year = 2020
    println("Brand: $brand, Year: $year")
}
Drag options to blanks, or click blank then click option'
Aapply
Bwith
Calso
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'also' which uses 'it' and is less convenient for property access.
Using 'let' which returns the lambda result, not the object.
Using 'with' which is not called as an extension function.
3fill in blank
hard

Fix the error in the code by choosing the correct function to initialize and return the object.

Kotlin
val book = Book().[1] {
    title = "Kotlin Guide"
    pages = 250
}
println(book.title)
Drag options to blanks, or click blank then click option'
Alet
Bapply
Crun
Dalso
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' or 'run' which return the lambda result, not the object.
Using 'also' which uses 'it' and is less convenient here.
4fill in blank
hard

Fill both blanks to create a mutable list and add elements using apply.

Kotlin
val numbers = mutableListOf<Int>()[1] {
    add(1)
    add(2)
    add(3)
}[2]
println(numbers)
Drag options to blanks, or click blank then click option'
Aapply
Blet
Calso
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' or 'run' which return the lambda result, not the list.
Using 'also' which uses 'it' and is less convenient for adding elements.
5fill in blank
hard

Fill all three blanks to create a data class instance, configure it with apply, and print its properties.

Kotlin
data class User(var username: String = "", var email: String = "")

val user = User()[1] {
    username = "john_doe"
    email = "john@example.com"
}

println("Username: ${user.[2], Email: ${user.[3]")
Drag options to blanks, or click blank then click option'
Aapply
Busername
Cemail
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' instead of 'apply' which returns the lambda result.
Misspelling property names in the print statement.
Using 'also' which uses 'it' and is less convenient here.