Hi All, I want to create extension function (like ...
# announcements
a
Hi All, I want to create extension function (like
run
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html) which returns nothing (
Unit
) (see code block).
towards
function purpose: run
block()
in scope of
T
. And if
block()
returns some result - it must be ignored. Kotlin-Dev Team, could you please recommend better name? And do you have plans to add same extension to language? Thank you in advance.
d
Already exists, it's called
run
.
a
n
If your block returns Unit, then
run
returns Unit, which (in Kotlin) is the same as returning no value.
E.g. your
towards
function will return Unit. If you don’t explicitly declare a result type of a block-structured function, Kotlin defaults the result type to Unit.
a
I know. I'm talking about solution without conditions. Yes, I need Unit
n
You mean you want to be able to pass in a block that would return non-Unit if passed to
run
, and force the result of the
towards
function to be Unit regardless?
a
towards
function purpose: run block() in scope of T. And if block() returns some result - it must be ignored.
n
👍
Q: is there a reason why this is required, instead of just ignoring the result of
run
?
E.g. reflection or static code analysis or somesuch
a
Simple - additional protection. No return-value - no problems with it 🙂
a
function purpose: run block() in scope of T. And if block() returns some result - it must be ignored.
@aerialist It looks like you are giving a definition of a side-effect . So maybe try to think in that direction:
effect
or
affect(ed)
, or
runEffect
, etc.
n
It’s convention to use
also
or
apply
for side effects. The
apply
extension method also discards any result from the block.
👆 1
Maybe that’s good enough?
a
No, because in case of
apply
I can continue my work with object. In
apply
docs: "... and returns
this
value." In case of
towards
I have nothing to return and my work with object is finished.