4 ms·
JSON and reflection, you know you gonna get a value once you'll have instantiated your object from a JSON description. So my var are lateninit because I don't n
by dimillian 10y ago
JSON and reflection, you know you gonna get a value once you'll have instantiated your object from a JSON description. So my var are lateninit because I don't need a ? or !!
- snuxoll 10y agoInitialize them with default values, then? Or if you're using Jackson there is a module from FasterXML that provides support for Kotlin data classes. lateinit is a crutch to get things working, not something you want to use long-term.
- dimillian 10y agoNever really thought about it, didn't even realise it was tied to Jetbrain and not build into Kotlin itself. I feel initialise a default value counter intuitive, what the default of a string , "", "default", "test". I know it works because it'll be reassigned with the JSON value later, but still feel dirty. I prefer the Swift way let value: String!
- nostrademons 10y agoWhy not use Jackson? I define the bulk of my JSON datatypes as: data class Foo( val bar: String, val baz: String, val quux: Int ) No nullables needed, unless the actual JSON spec calls for a nullable field, in which case I want the compiler to remind me to handle the null case. Jackson handles everything out-of-the-box; it has no problem with constructor injection, and requires no annotations for the default case. For circular structures & injected values, I make them 'var' and inject after construction. This is a bit icky but generally manageable; if I get too uncomfortable with it, I can move the property declaration to the body, make it private set, and provide an accessor to handle all the injection at once.
- afastow 10y agoLateinit is good for what it is designed for which is allowing for fields that are always going to be initialized before use but after construction, normally by a library. I wouldn't describe it as a crutch in that case. It'd be ideal if libraries were better about using constructor injection when possible, but I think there are some valid scenarios where circular dependencies make it impossible to use only constructor injection.
- snuxoll 10y ago> It'd be ideal if libraries were better about using constructor injection when possible, but I think there are some valid scenarios where circular dependencies make it impossible to use only constructor injection. Thankfully it is rare to require circular dependencies, but this is probably the one use case where lateinit is certainly warranted.
- vbezhenar 10y agolateinit is bad, because it forces you to use var. If you're using var, you can change this value later and you want the language to prevent that (unless you want a mutable property, of course).
- deleted 10y ago[deleted]
- lenkite 10y agoYou can use constructors for JSON now. See https://github.com/FasterXML/jackson-module-kotlin https://github.com/FasterXML/jackson-module-kotlin