0
0
Kotlinprogramming~10 mins

Sealed classes for restricted hierarchies 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'
AShape
BShapes
Cshape
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 of the sealed class Shape.

Kotlin
class Circle(val radius: Double) : [1]()
Drag options to blanks, or click blank then click option'
AshapeClass
Bshape
CShape
DShapes
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect class names or lowercase names for inheritance.
3fill in blank
hard

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

Kotlin
fun area(shape: Shape): Double = when(shape) {
    is Circle -> Math.PI * shape.radius * shape.radius
    is Square -> shape.side * shape.side
    [1] -> throw IllegalArgumentException("Unknown shape")
}
Drag options to blanks, or click blank then click option'
Adefault
Belse
Cotherwise
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid keywords like default or catch instead of else.
4fill in blank
hard

Fill both blanks to declare a sealed class Shape with two subclasses Circle and Square.

Kotlin
sealed class [1] {
    class Circle(val radius: Double) : [2]()
    class Square(val side: Double) : Shape()
}
Drag options to blanks, or click blank then click option'
AShape
Bshape
CShapes
DshapeClass
Attempts:
3 left
💡 Hint
Common Mistakes
Using different or lowercase names for the sealed class or superclass.
5fill in blank
hard

Fill all three blanks to create a sealed class Shape with subclasses Circle and Square, and a function to calculate area.

Kotlin
sealed class [1] {
    class Circle(val radius: Double) : [2]()
    class Square(val side: Double) : Shape()
}

fun area(shape: [3]): Double = when(shape) {
    is Circle -> Math.PI * shape.radius * shape.radius
    is Square -> shape.side * shape.side
}
Drag options to blanks, or click blank then click option'
AShape
Bshape
DShapes
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent or incorrect class names.