You're dealing with an abstract data structure, a Map, and the code doesn't really care about how that map was populated with values, nor should it. Re #2, are you thinking that your context might be different because I was manually creating the map in the example I gave? Not sure what "data values is dynamic" has to do with any difficulties you're having. Was there a runtime exception or a compiler error? Did you get unexpected results? Tell us exactly how things "didn't work."Ģ. "It didn't work" doesn't really tell us much. I try the following code but still didn't work The compiler, of course, always wins in these type of situations so when in doubt, I'll explicitly declare the type I want to deal with so that I can help the IDE/compiler point out invalid expressions according to my intent, not what the compiler has inferred according to its inference algorithms. Regarding type-safety and making sure you and the compiler are on the same page, there have been a few instances where I thought I was dealing with one type but the compiler interpreted what I had written as being of a different type. Use type inference judiciously declare explicit types for clarity and safety (to make sure you and the compiler are on the same page). In Kotlin, it appears the idiom is to use the built-in factory methods like mapOf and arrayOf when possible.ģ. Declarations should use generic types, like List and Map. Even with Java code, you shouldn't be declaring any variables as ArrayList or HashMap. As Stephan has already mentioned, avoid using specific implementations like HashMap and ArrayList. It seems to you have previously programmed in Java and have carried over some poor habits from working in Java.Ģ. Again, making Product immutable will require a shift in the way you're thinking about your program objects. You might also be able to keep your Product data class immutable as well:ĭata class Product(val name: String, val availableQuantity: Int)Īlthough I'd have to see more details of how you're using it. This leads to non-functional code: var data: Map> That being said, I think I have a pretty decent handle on some of the Kotlin idioms. If you don't mind, a few comments on style.Ĭaveat: I've just recently started out with Kotlin myself so there may be better and more idiomatic ways than what I'm about to suggest below.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |