mirror of
https://github.com/jlengrand/kotlin.git
synced 2026-05-16 15:53:55 +00:00
Simplify ifs when branches have condition true/false.
Simplify blocks containing only a variable declaration
and a variable get of the same variable. Simplify to
just the condition.
Do not introduce temporary variables for constants for
null checks. Constants have no side-effects and can be
reloaded freely instead of going through a local.
This simplifies code such as "42.toLong()!!" so that the
resulting code has no branches and uses no locals. The
simplifications happen as follows:
```
block
temp = 42.toLong()
when
(temp == null) throw NPE
(true) load temp
---> null test simplification
block
temp = 42.toLong()
when
(false) throw NPE
(true) load temp
---> when simplification
block
temp = 42.toLong()
load temp
---> block simplification
42.toLong()
```
39 lines
648 B
Kotlin
Vendored
39 lines
648 B
Kotlin
Vendored
class MyString {
|
|
var s = ""
|
|
operator fun plus(x : String) : MyString {
|
|
s += x
|
|
return this
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return s
|
|
}
|
|
}
|
|
|
|
|
|
fun test1() : MyString {
|
|
var r = MyString()
|
|
try {
|
|
r + "Try1"
|
|
|
|
try {
|
|
r + "Try2"
|
|
if (true)
|
|
return r
|
|
} finally {
|
|
r + "Finally2"
|
|
if (true) {
|
|
return r
|
|
}
|
|
}
|
|
|
|
return r
|
|
} finally {
|
|
r + "Finally1"
|
|
}
|
|
}
|
|
|
|
|
|
fun box(): String {
|
|
return if (test1().toString() == "Try1Try2Finally2Finally1") "OK" else "fail: ${test1()}"
|
|
} |