Johann Pardanaud
11/24/2023, 2:50 PMval list: List<Int> = listOf(1,2,3)
list
.firstOrNull()
?: -1
.toString()
.padStart(2, '0')
I would like to apply .toString().padStart(2, '0')
to the result of list.firstOrNull() ?: -1
. But, due to Kotlin's precedence, it is only applied to -1
.Johann Pardanaud
11/24/2023, 2:53 PMSam
11/24/2023, 2:58 PM(list.firstOrNull() ?: -1)
.toString()
.padStart(2, '0')
Sam
11/24/2023, 2:59 PMgetOrElse(0) { ... }
CLOVIS
11/24/2023, 2:59 PMval first = list
.firstOrNull()
?: -1
first.toString()
.padStart(2, '0')
Johann Pardanaud
11/24/2023, 3:01 PMJohann Pardanaud
11/24/2023, 3:02 PMJacob
11/24/2023, 3:14 PMJohann Pardanaud
11/24/2023, 3:14 PMCLOVIS
11/24/2023, 3:15 PMlet
everywhere.Johann Pardanaud
11/24/2023, 3:18 PMYoussef Shoaib [MOD]
11/24/2023, 3:45 PMinline fun <T: Any> T?.ifNull(replacement: () -> T) = this ?: replacement()
Charles Flynn
11/25/2023, 7:07 AMfirstOr(X)
then you have
list
.firstOr(-1)
.toString()
.padStart(2, '0')
Charles Flynn
11/25/2023, 8:11 AMorNull()
variants so as to not throw exceptions. I wonder if a more general or()
version in those contexts would be useful (as well as the null version). There's always :?
or other functions to deal with the null version but if ultimately you're looking for a default then it's just extra noise.