Sam Stone
11/06/2022, 1:31 AMequals
, when should you use if(condition) { return true } else {}
and when should you leave out the else, and use implicit flow control (it is by definition else because it didn’t return). Is there a performance impact in including else
?Chris Lee
11/06/2022, 1:53 AMelse
to the extent possible. in say equals()
if would be if(condition) return false
with objects being equal only if they make it all the way through the conditions. No performance change for implicit flow control (absence of else
).ephemient
11/06/2022, 8:38 AMelse
is fine (and necessary) if you lift the return
out, e.g.
return if (condition) { true} else { ... }
and if you can get it all the way to the top level, you can define the function as = expression
instead of { block }
ephemient
11/06/2022, 8:39 AMelse
when it introduces unnecessary nesting, unless it is specifically clearer in some circumstanceephemient
11/06/2022, 8:40 AMequals
can be defined by a simple expression though, e.g.
class Foo(val foo: String) {
override fun equals(other: Any?): Boolean =
other is Foo && this.foo == other.foo
override fun hashCode(): Int = /* must override hashCode when overriding equals */
Chris Lee
11/06/2022, 2:23 PMequals
can’t be represented in a single if
expression:
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as OtherType
if (url != other.url) return false
if (value != other.value) return false
return true
}
However, it can be collapsed into a when statement:
override fun equals(other: Any?): Boolean {
return when {
this === other -> true
javaClass != other?.javaClass -> false
other !is OtherType -> false
url != other.url -> false
else -> true
}
}
ephemient
11/06/2022, 7:19 PMfinal
(as the default in Kotlin is) that extra check is not requiredelizarov
11/08/2022, 12:17 PMSam Stone
11/08/2022, 2:48 PMelizarov
11/08/2022, 4:30 PM