I don't want to specify initializer for local, nullable or primitive variable


#1

Latest koltin enforce me to specify initializer for local variable.

before:
{code}

  1. val doneAsync:Boolean
  2. try {
  3. doneAsync = task(pageManager.getDom(tabId), it)
  4. }
  5. finally {
  6. if (!doneAsync) {
  7. it()
  8. }
  9. }{code}


after:
{code}

  1. var doneAsync = false
  2. try {
  3. doneAsync = task(pageManager.getDom(tabId), it)
  4. }
  5. finally {
  6. if (!doneAsync) {
  7. it()
  8. }
  9. }{code}


OMG. Fucking stupid Java. I want to specify doneAsync as immutable value, not as variable. And now (after yeasterday commits) I cannot.

before:
{code}

  1. var candidates:MutableList<Tab>?
  2. var newTab:Tab?
  3. var existingTab:Tab?
  4. for (tab in it) {…{code}


after:
{code}

  1. var candidates:MutableList<Tab>? = null
  2. var newTab:Tab? = null
  3. var existingTab:Tab? = null
{code}
WTF. Why “?” (specify nullable) is not enough?

Are you sure that we need these changes?


#2

Apparently you want http://youtrack.jetbrains.com/issue/KT-2957. Please vote =)

Not nullable types (except corresponding to primitives) obviously can’t have default values.

Primitives theoretically can, but it seems to me better to write values explicitly:

var sum: Int
for (el in list) {
  sum += el
}

Here

var sum = 0

will be much better!
The same with booleans.

As for the first example, ‘doneAsync’ is semantically mutable variable (like ‘v’ here):

    val v: Boolean?
  try {
  doSmth(v)  // If you’re able to use v with default ‘null’ value here
  v = true   // and reassign v here,
  doSmth(v)  // then ‘v’ behaves as a mutable variable, so it should be a var.
  }
  finally {
  if (!v) {  
  }
  }

#3

first example for me equals to:

``

val doneAsync = task(pageManager.getDom(tabId), it)

if (!doneAsync) {
  it()
}

But I need to use try-finally. In Java I cannot use “final” modifier in this case (it is sad :)) and now I cannot do it in Kotlin. May be it is semantically correct, but really doneAsync is immutable (i.e. I must not modify it’s value). I don’t want change val to var only due to try-finally.


#4

The problem is not modification, but initialization. You never modify doneAsync, but then you may never initialize it when you reach 'finally'.