nkiesel
01/03/2019, 7:03 AMtry/catch
in init blocks to initialize immutable (i.e. val
) class properties? Right now I use
class Foo(val a: Int) {
val b: Int
init {
var bb: Int
try {
bb = complicated(a)
catch (e: Excepetion) {
bb = fallback()
}
b = bb!!
}
Czar
01/03/2019, 7:16 AMclass Foo(val a: Int) {
val b: Int
init {
b = try {
complicated(a)
} catch (e: Exception) {
fallback()
}
}
Czar
01/03/2019, 7:17 AMclass Foo(val a: Int) {
val b: Int = try {
complicated(a)
} catch (e: Exception) {
fallback()
}
}
Czar
01/03/2019, 7:21 AMclass Foo(a: Int)
nkiesel
01/03/2019, 7:01 PMtry
? I tied val (b, c) = try {...}
but that produces a syntax error. val p = try {...}; val b = p.first; val c = p.second
works but looks uglyShawn
01/03/2019, 7:05 PMShawn
01/03/2019, 7:06 PMp
is, you can define .component1()
and .component2()
such that they return first and second, respectivelyShawn
01/03/2019, 7:07 PMShawn
01/03/2019, 7:07 PMPair
from the try/catch though it’s not the most intuitiveShawn
01/03/2019, 7:19 PMval (a, b) = try {
mightThrow()
} catch (_: Exception) {
default()
}
}
fun mightThrow() = 1 to 2
fun default() = 3 to 4
nkiesel
01/03/2019, 7:51 PMtry
did return a Pair
) but Intellj showed a syntax error for this when I used this approach for class properties. It did work for local values in functionsShawn
01/03/2019, 7:52 PMnkiesel
01/03/2019, 8:03 PMclass foo() {
private fun mightThrow() = 1 to 2
private fun default() = 3 to 4
val a: Int
val b: Int
init {
val p = try {
mightThrow()
} catch (_: Exception) {
default()
}
a = p.first
b = p.second
}
}