Is there an equivalent of `check` that would take ...
# getting-started
p
Is there an equivalent of
check
that would take a supplier lambda for the case when the check passes?
a
like run this lambda on success, otherwise throw an exception?
n
something.takeIf { check(it) }?.run(lambda) ?: throw Exception()
like so ? should be simple enough as a extension function for your needs
p
@Andreas Sinz yeah @Nikky
check()
does not return Boolean
a
I'm not aware of any function in the stdlib, but its trivial to write your own:
Copy code
inline fun checkOnSuccess(value: Boolean, onSuccess: () -> Unit) {
    if(value) 
        onSuccess() 
    else 
        throw IllegalStateException()
}
p
Isn’t it equivalent to this?
Copy code
check(value)
onSuccess()
Everything after
check()
is executed only if
value
is
true
, otherwise exception is thrown.
r
@poohbar If you want the functionality of
check
(i.e. continue on true, throw on false), what @Pavlo Liapota suggested should do the trick. If you just want to return a
Boolean
, you're already passing in a
Boolean
so what does a new function get you over
if
?
p
yeah it works great, i just wanted to use it in a method without full body
so i needed to have just one statement
i had:
Copy code
fun foo() = if (condition) value else throw IllegalStateException()
and i wanted to use
check()
instead
r
Any particular reason why it needs to be disembodied? I've noticed many times people code themselves into a corner in Kotlin trying desperately to fit separate logical statements into one line.
👆 2
p
no reason, I was just wondering
👍 1
i am not a big fan of how the syntax for property getters work and they look a bit better if they don't have a body
Copy code
val value: Type = initialValue
    get() {
        // do something here
    }
this just looks odd to me.. too much indentation
r
Interesting. I've actually always found it cleaner than other property enabled languages.
With one exception:
field
I really hate
field
. Personally I think it would make far more sense in the setter to use the properties name as the backing field, and if you do want to call the setter or getter recursively, use
this.<propertyName>
.
But that's just me 🙂
p
oh yeah that would be way better, agreed