0
0
Kotlinprogramming~10 mins

Sealed classes with when exhaustive check 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 declare a sealed class named Shape.

Kotlin
sealed class [1]
Drag options to blanks, or click blank then click option'
AclassShape
BShape
Cshape
DsealedShape
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or incorrect class names.
Adding extra words to the class name.
2fill in blank
medium

Complete the code to define a data class Circle inheriting from Shape with a radius property.

Kotlin
data class Circle(val radius: Double) : [1]()
Drag options to blanks, or click blank then click option'
AShape
Bshape
CCircle
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'shape' instead of 'Shape'.
Trying to inherit from the same class name.
3fill in blank
hard

Fix the error in the when expression to make it exhaustive for Shape.

Kotlin
fun area(shape: Shape): Double = when(shape) {
    is Circle -> Math.PI * shape.radius * shape.radius
    is Rectangle -> shape.width * shape.height
    [1]
}
Drag options to blanks, or click blank then click option'
Ais Shape -> 0.0
Bis Square -> shape.side * shape.side
Celse -> 0.0
Dis Triangle -> 0.5 * shape.base * shape.height
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the else branch causing compilation error.
Adding incorrect or incomplete subclass checks.
4fill in blank
hard

Fill both blanks to create a when expression that is exhaustive without else, covering all subclasses.

Kotlin
fun describe(shape: Shape): String = when(shape) {
    is Circle -> "Circle with radius ${shape.radius}"
    [1] -> "Rectangle with width ${shape.width} and height ${shape.height}"
    [2] -> "Square with side ${shape.side}"
}
Drag options to blanks, or click blank then click option'
Ais Rectangle
Bis Square
Cis Triangle
Delse
Attempts:
3 left
💡 Hint
Common Mistakes
Using else instead of subclass names.
Missing one subclass causing non-exhaustive error.
5fill in blank
hard

Fill all three blanks to create a sealed class hierarchy and an exhaustive when expression that returns area.

Kotlin
sealed class [1]
data class Circle(val radius: Double) : [1]()
data class Rectangle(val width: Double, val height: Double) : [1]()
fun area(shape: [1]): Double = when(shape) {
    is Circle -> Math.PI * shape.radius * shape.radius
    is Rectangle -> shape.width * shape.height
}
Drag options to blanks, or click blank then click option'
AShape
BCircle
CRectangle
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Using different class names in inheritance.
Using 'sealed' keyword instead of class name.