Hi all. I ran into an interesting little problem ...
# announcements
Hi all. I ran into an interesting little problem with type inference producing a counter-intuitive result. It's not a bug, but it's maybe an example of an undesirable side-effect of the way things are specified right now.I was playing around with JKid, and writing a new unit test, and I had code like this:
Copy code
private val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz")
   private val value = TimeWithZone(df.parse("2017-08-18 17:25:26.632 PDT"))    

    @Test fun testDeserialization() {
       println("deserialize gives " +  deserialize(json))
       assertEquals(value, deserialize(json))
This failed with a ginormous stack backtrace, deep in the bowels of reflection, telling me it couldn't find a field of TimeWithZone. The fix is compact enough:
Copy code
println("deserialize gives " + deserialize<TimeWithZone>(json))
OK, so in the assertEquals, type inference is used to make the call of deserialize<Any> into a call of deserialize<TimeWithZone>, whereas in a println, it's not. Reasonable enough, I guess, but a little non-obvious. Intuitively, I just don't expect an expression to change meaning based on where it's used. In this case, I'd actually rather that type inference hadn't made the assertEquals call work, and instead had forced me to type deserialize<TimeWithZone>(...) in the first place. I'm sure there's a case to be made for the more eager type inference that Kotlin has today, but I just thought I'd throw this out there as maybe an unintended and undesirable side-effect. I could see this behavior causing a lot of confusion, particularly for someone coming from a less statically-typed background.
(surround code with ``` to fix the formatting)
This "upwards" generic inference often helps shortening code and avoiding duplication, especially in things like lambdas.
Makes sense, certainly. It still feels like this is a bit of a landmine, though. That said, I don't have any ideas to improve things that I'm all that happy with.