Skip to content

Instantly share code, notes, and snippets.

@joshlong
Created November 12, 2024 20:54
Show Gist options
  • Save joshlong/53fd8bddd0973a512454dc758eff550a to your computer and use it in GitHub Desktop.
Save joshlong/53fd8bddd0973a512454dc758eff550a to your computer and use it in GitHub Desktop.
an example demonstrating how nice Kotlin can be
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