Last active
May 4, 2019 18:59
-
-
Save pufface/ffee5734ac876839c5ec2b5c06fc56dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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