Skip to content

Commit 17bc383

Browse files
authored
Create 34_1_enum_class
enum class in kotlin
1 parent 17fd1b0 commit 17bc383

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/34_1_enum_class

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
interface ICardCashBack {
3+
fun getCashbackValue(): Float
4+
}
5+
6+
enum class CreditCardType(val color: String, val maxLimit: Int = 1000000): ICardCashBack {
7+
SILVER("gray", 50000) {
8+
override fun getCashbackValue(): Float = 0.02f
9+
},
10+
GOLD("gold"){
11+
override fun getCashbackValue(): Float = 0.04f
12+
},
13+
PLATINUM("black"){
14+
override fun getCashbackValue(): Float = 0.06f
15+
}
16+
}
17+
18+
19+
fun main() {
20+
21+
/* Access properties and methods */
22+
println(CreditCardType.SILVER.color) // gray
23+
println(CreditCardType.SILVER.getCashbackValue()) // 0.02
24+
25+
/* Enum constants are objects of enum class type. */
26+
val peterCardType: CreditCardType = CreditCardType.GOLD
27+
28+
/* Each enum object has two properties: ordinal and name */
29+
println(CreditCardType.GOLD.ordinal)
30+
println(CreditCardType.GOLD) // OR CreditCardType.GOLD.name
31+
32+
/* Each enum object has two methods: values() and valueOf() */
33+
val myConstants: Array<CreditCardType> = CreditCardType.values()
34+
myConstants.forEach { println(it) }
35+
36+
/* Using in 'when' statement */
37+
when(peterCardType) {
38+
CreditCardType.SILVER -> println("Peter has silver card")
39+
CreditCardType.GOLD -> println("Peter has gold card")
40+
CreditCardType.PLATINUM -> println("Peter has platinum card")
41+
}
42+
}

0 commit comments

Comments
 (0)