Smartcast for var


#1

Sometimes, I need a mutable, nullable variable. I understand that Smartcast is usually not possible for them because of race conditions, but I would like to propose an annotation or keyword for a var to mark it as “threadsafe” or something like that. For example, see this code:

var progBar: FileProgressBar? = null
fun foo() {
  progBar = FileProgressBar(release.toString())
  val l = progBar!!.label
  reg(progBar!!.progressBar, constraints(1).setWeights(0.6))
  add(progBar!!.progressLabel, constraints(2).setWeight(0.2))
}

Since progBar needs to be accessable elsewhere, it is a nullable var and no I cannot use lateinit. What I know, however, is that there is NEVER a method that may set progBar to null while foo is running, so I would like to avoid these ugly !! qualifiers…


#2

This has already been discussed here: Smart casts and nullability in single-threaded contexts


#3

And to no avail I see…


#4

But a smartcast is not needed in your case, I see now. apply can be used:

var progBar: FileProgressBar? = null
fun foo() {
  progBar = FileProgressBar(release.toString()).apply {
    val l = label
    reg(progressBar, constraints(1).setWeights(0.6))
    add(progressLabel, constraints(2).setWeight(0.2))
  }
}

#5

Alternative solution if you don’t want to lose the explicit reference to the progressbar:

var progBar: FileProgressBar? = null
fun foo() {
  progBar = FileProgressBar(release.toString()).also { progBar ->
    val l = progBar.label
    reg(progBar.progressBar, constraints(1).setWeights(0.6))
    add(progBar.progressLabel, constraints(2).setWeight(0.2))
  }
}