Created
November 12, 2024 20:54
-
-
Save joshlong/53fd8bddd0973a512454dc758eff550a to your computer and use it in GitHub Desktop.
an example demonstrating how nice Kotlin can be
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
data class Point(val x: Int, val y: Int) | |
data class Rectangle(val width: Int, val height: Int) | |
data class Circle(val radius: Int) | |
fun describePoint(point: Point) = when (point) { | |
Point(0, 0) -> "Origin" | |
Point(1, 2) -> "1,2" | |
else -> throw IllegalStateException("Unexpected value: $point") | |
} | |
fun calculateArea(shape: Any): Double = when (shape) { | |
is Rectangle -> (shape.height * shape.width).toDouble() | |
is Circle -> Math.PI * shape.radius * shape.radius | |
else -> throw IllegalArgumentException("Unknown shape") | |
} | |
val point = Point(1, 2) | |
println(describePoint(point)) | |
val shape = Circle(5) | |
val area = calculateArea(shape) | |
println("Area of the shape: $area!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment