0
0
Android Kotlinmobile~10 mins

Sealed classes in Android 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 declare a sealed class named Shape.

Android Kotlin
sealed class [1]
Drag options to blanks, or click blank then click option'
AShape
Bshape
CShapes
DshapeClass
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or plural forms for the class name.
2fill in blank
medium

Complete the code to declare a subclass Circle inside the sealed class Shape.

Android Kotlin
sealed class Shape {
    data class [1](val radius: Double) : Shape()
}
Drag options to blanks, or click blank then click option'
ASquare
BCircle
CTriangle
DRectangle
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different shape name than Circle.
Forgetting to inherit from Shape.
3fill in blank
hard

Fix the error in the when expression to handle all Shape subclasses without else.

Android Kotlin
fun area(shape: Shape): Double = when(shape) {
    is Shape.Circle -> 3.14 * shape.radius * shape.radius
    is Shape.Square -> shape.side * shape.side
    [1]
}
Drag options to blanks, or click blank then click option'
Aelse -> 0.0
Bis Shape.Shape -> 0.0
Cis Shape.Triangle -> 0.5 * shape.base * shape.height
Dis Shape.Rectangle -> shape.length * shape.width
Attempts:
3 left
💡 Hint
Common Mistakes
Using else instead of explicit subclass cases.
Adding a case for the sealed class itself.
4fill in blank
hard

Fill both blanks to declare two subclasses Rectangle and Triangle inside sealed class Shape.

Android Kotlin
sealed class Shape {
    data class [1](val length: Double, val width: Double) : Shape()
    data class [2](val base: Double, val height: Double) : Shape()
}
Drag options to blanks, or click blank then click option'
ARectangle
BCircle
CTriangle
DSquare
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up class names or using unrelated names.
5fill in blank
hard

Fill all three blanks to create a when expression that returns area for each Shape subclass.

Android Kotlin
fun area(shape: Shape): Double = when(shape) {
    is Shape.Circle -> 3.14 * shape.radius * shape.radius
    is Shape.Rectangle -> shape.length * shape.width
    is Shape.Triangle -> [1] * shape.base * shape.height
}
Drag options to blanks, or click blank then click option'
A3
B1
C2
D0.5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2 or 3 instead of 0.5.
Forgetting the multiplier.