


Unfortunately, Java doesn't support that yet but things have been improved with the factory methods for collection in JDK 9 and it's almost like that. to create a list of 1, 2, 3 you can simply write val items = listOf(1, 2, 3). If you have worked in Groovy or Kotlin then you know that how easy is to create the list with elements using collection literals e.g. The JEP stands for the JDK enhancement proposal. However, a type mismatch between the json data what the object requires is something i will look to refine to have the best reporting the the message received was not correctly formatted.Hello guys, this is my first article in Java 9 features on this blog, and today you'll learn about my favorite feature "factory methods for collection", which is introduced as part of JEP 269. This is for instancing from within a library.Īs this is in no way a replacement for normal instancing, and only for converting data received as json into object for cleaner processing, the performance is fine. Where code instances these same classes, they should be instanced the normal way. This is not an alternative declaration syntax within the code. Also requires classes declared to describe data to also need to declare an extension function. Hard to see how code which has only the class in variable can use the extension function. This code will have found the relevant class to instance by lookup from a map. So objects will be instanced within the method processing the json. The extension function is not really useful as the goal is instancing objects from data received as json at run time. I foolishly tried that with in place of, so again thank you. Thank You! I am bringing code across to Kotlin, and not having not used Java for over 10 some of the nuances I am still getting. I can instance a dummy instance of the class and have: val test = instance(dcInstance, map)īut creating a dummy member of the class is just messy. Unfortunately val classVal = DC::classĭoes not work. I still need to look at defaults, but the main hurdle for me is be able to call ‘instance’ with a variable in place ‘’ where the class is explicitly in the call. Println("testData is $testData") // testData is DC(str=six, num=6) Val testData = instance(mapOf("str" to "six","num" to 6)) Which can be used as follows: data class DC(val str:String="",val num:Int=0) Consider: data class DC(val str:String="",val num:Int=0)) This can be done in part using an alternate constructor, but not in a generic way. I have a library for an application where there is a need to instantiate objects from a map of the parameters.
