Allan Caine
1 min readMay 17, 2018

--

Here is another approach. It uses a sealed class. The area is a abstract val. An else branch of a when expression is not needed. The compiler knows the three possible subclasses of the sealed class Shapes.

sealed class Shapes {

abstract val area : Float

fun nameType() : String {
return when(this) {
is Circle -> "Circle"
is Square -> "Square"
is Rectangle -> "Rectangle"
}
}

data class Circle(val radius : Float) : Shapes() {
override val area: Float
get() = Math.PI.toFloat() * radius * radius
}
data class Square(val side: Float) : Shapes() {
override val area: Float
get() = side * side
}
data class Rectangle(val length : Float, val width: Float) : Shapes() {
override val area: Float
get() = length * width
}
}

fun main(args: Array<String>) {
val circle = Shapes.Circle(radius = 8.8f)
println(circle.area) // 243.28496
println(circle.nameType()) // Prints Circle

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Allan Caine
Allan Caine

Written by Allan Caine

Senior Android Developer, TD Bank (Canada) (Opinions are my own)

No responses yet

Write a response