The enum class and functions

Just as the enum class can have a property, it can also have a function. Let's create an application in which we can store the land area of different states:

enum class US (val totalArea : Double, val landArea : Double) {
NEWYORK (141_297.0, 122_057.0),
VIRGINIA (110_787.0, 102_279.0) ,
HAWAII (28_313.0, 16_635.0),
NEWJERSEY (22_591.0, 19_047.0) ;

fun getWaterArea() = totalArea - landArea
}

Although we don't often use semicolons in Kotlin, we do need to place a semicolon at the end of a list when the enum class contains a constructor with more than one property. enum class US contains different states, each of which contain information about the land and total area. The enum class contains the getWaterArea function, which returns information about the water area of each state:

fun main(args: Array<String>) {

println("Square kilometer")
for (state in US.values()){
println("$state state's total area is ${state.totalArea} and " +
"Land area is ${state.landArea}" )
println("Water area " + state.getWaterArea())
}
}

Get a list of all the states using the values() function, iterate over it, and print the information on the screen:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.10.32