Wrapping with `let` hides the uninitialized variab...
# getting-started
a
Wrapping with
let
hides the uninitialized variable being null. Is there an explanation regarding this? Seems Kotlin (1.6.21) is not null-safe in this situation.
Copy code
class SomeClass { // extremely minified code

  val foo = let { bar } // compile error (almost broke production but my unit test captured it)
  // val foo = bar // compile error (safe!)
    
  val bar = true
}
e
you can easily write
Copy code
class SomeClass {
  val foo = bar()
  val bar = true
  private fun bar() = bar
and see an uninitialized variable there as well
there's no way to fix this in the language without breaking existing valid code, but there's some discussion on https://youtrack.jetbrains.com/issue/KT-10455 if you want to follow
a
Thanks! I was sure something so basic would have an existing discussion thread already, so I was mainly looking for such. Thanks 🙂
k
In the above examples from both Allan and ephemient,
SomeClass().foo
is initialized to
false
. I thought this discussion is saying it's uninitialized.
r
On the JVM, uninitialized values have a default "zero" value when declared. For primitive numbers, that will be
0
, for `boolean`s it will be
false
, and for references it will be
null
. Essentially, when you declare a value on the JVM, it has memory allocated for it and all the bits are set to
0
, which is interpreted as I mentioned above. (That implementation detail will eventually be important when Project Valhalla ever happens.)
👍 1
a
Ah good point! My example was bad. The original code has a
List<T>
type which is null if uninitialized.
👍 1
https://kotlinlang.slack.com/archives/C0B8MA7FA/p1654695229040699?thread_ts=1654683226.436529&amp;cid=C0B8MA7FA This one sounds scarier as it won’t even crash 😄, just silently reach a potentially illegal state