I need to get the value of the Map, and handle exceptions, but I can’t find any examples, would someone be so kind?
data class Product(val details:String?,val price:Double)
val producTable = mutableMapOf<Int,Product>()
producTable.put(1,Product( "Mouse Usb xxxx",3.25))
producTable.put(2,Product( "Keyboard Usb xxxx",4.25))
producTable.put(3,Product( "Pendrive 16gb xxxx",2.25))
val nid:Int=0
val result=producTable.getValue(nid)
println(result.details)
Exception in thread "main" java.util.NoSuchElementException: Key 0 is missing in the map.
data class Product(val details:String?, val price:Double)
val productTable = mutableMapOf<Int,Product>()
productTable[1] = Product( "Mouse Usb xxxx", 3.25)
productTable[2] = Product( "Keyboard Usb xxxx", 4.25)
productTable[3] = Product( "Pendrive 16gb xxxx", 2.25)
val nid:Int = 0
val result = producTable[nid]
println(result?.details ?: "Product not found")
Alternatively, you can check the map first with containsKey. Generally, just have a look what operations work on maps, you can write much nicer code than in Java: Map-specific operations | Kotlin Documentation
@vmercadolibretuc as an alternative, you can also use withDefault to create a map that’ll return some default value from getValue (but not from [] or get) for keys not present in the map.
Though this solves the problem but it can lead to another problem like NPE when you try something on return value. So maybe using withDefault is better wdyt ?
This is depends on specific business logic you need.
NPE is not a problem in Kotlin as the type of the result value is Product? and compiler won’t let you forget to handle null case. Beauty of the strong typing with nullable classes