Skip to content

Instantly share code, notes, and snippets.

@pufface
Last active May 4, 2019 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pufface/ffee5734ac876839c5ec2b5c06fc56dc to your computer and use it in GitHub Desktop.
Save pufface/ffee5734ac876839c5ec2b5c06fc56dc to your computer and use it in GitHub Desktop.
sealed class Shape
class Square(val side: Double) : Shape()
class Circle(val radius: Double) : Shape()
class Rectangle(val width: Double, val height: Double) : Shape()
fun main() {
val shapes = listOf(
Square(5.0),
Circle(4.0),
Rectangle(6.0, 7.0)
)
fun area(shape: Shape) = when (shape) {
is Square -> shape.side * shape.side
is Circle -> shape.radius * shape.radius * Math.PI
is Rectangle -> shape.height * shape.width
}
val totalArea = shapes.sumByDouble { area(it) }
println("Total area: $totalArea")
fun perimeter(shape: Shape) = when (shape) {
is Square -> 4 * shape.side
is Circle -> 2 * Math.PI * shape.radius
is Rectangle -> 2 * shape.height + 2 * shape.width
}
val totalPerimeter = shapes.sumByDouble { perimeter(it) }
println("Total perimeter: $totalPerimeter")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment