y
01/03/2023, 12:39 PMreturn@
considered harmful or unidiomatic?
for example, I want to make a function that sums up the number of values of a list, or returns null
if a certain value is detected. I wrote it as
fun List<Foo>.calcSum() = this.fold(0) { sum, val -> if (something) { sum + val } else { return@calcSum null } }
is this bad style?
I had to add a type hint for the function to even compile.Vampire
01/03/2023, 1:14 PMVampire
01/03/2023, 1:15 PMval
by value
and replace the undefined types to have
fun List<Int>.calcSum() = this.fold(0) { sum, value -> if (kotlin.random.Random.nextBoolean()) { sum + value } else { return@calcSum null } }
I get
Type mismatch: inferred type is Int but Nothing? was expected
Vampire
01/03/2023, 1:16 PM@calcSum
is redundant here as a simple return
would have the same effect.Vampire
01/03/2023, 1:19 PMfun List<Int>.calcSum(): Int? = this.fold(0) { sum, value -> if (kotlin.random.Random.nextBoolean()) { sum + value } else { return null } }
while I personally would use an extension property
val List<Int>.sum: Int? get() = this.fold(0) { sum, value -> if (kotlin.random.Random.nextBoolean()) { sum + value } else { return null } }
Vampire
01/03/2023, 1:20 PMJacob
01/03/2023, 1:35 PMy
01/03/2023, 1:55 PM-1
, followed by a .takeIf { it >= 0 }
Klitos Kyriacou
01/03/2023, 1:58 PMy
01/03/2023, 2:00 PMreturn@
, except it would return from the fold
rather than the function.
all in all, not an improvement. this is a problem that requires either two passes (one pass to verify input, second pass to sum) or one pass with short-circuiting. I do think return@
is the right solution here.thanksforallthefish
01/03/2023, 2:06 PMfun List<Foo>.calcSum() =
if (!something) null
else this.fold(0) { sum, val -> sum + val }
canāt something like this work? or is something
depending on val/sum
? (I find it more readable, donāt know about idiomatic)y
01/03/2023, 2:11 PMsomething
is a property of one of the values so it is discovered on-the-fly.
for example if Foo
is a sealed class
with one ānumberā variant and one ānot a numberā variant, and you want to sum a List<Foo>
such that a sum is null
if any of the values is not a number.y
01/03/2023, 2:12 PMfold
function with a closure that allows short-circuiting.Jacob
01/03/2023, 2:12 PMy
01/03/2023, 2:15 PMMatteo Mirk
01/05/2023, 1:06 PMreturn@
has its usages, mostly for returning from lambdas to enclosing functions
https://kotlinlang.org/docs/returns.html#return-to-labels