in java i can do: ```if(x!=null && x.name....
# announcements
j
in java i can do:
Copy code
if(x!=null && x.name.equals("name"))
{}
first evaluate if x is not null then second condition, second condition is not checked if x is null and then is false since && operator only true when all its true, must stop evaluating second condition, is this by desing? how could I do this in kotlin?
d
That should be copy-paste compatible with kotlin.
s
you can do exactly this ( safely, thanks to smart-casting), but you might also consider the more idiomatic
if (x?.name == "name")
or
if (x != null && x.name == "name")
if you want the short-circuit semantics to be obvious
j
now is working, thanks for your help
m
you might also consider
takeIf
-
x?.takeIf { it.name == "name" }?.let { ... }
👎 1
d
These idioms start to concern me after awhile -- they 'seem' overtly ineffecient, proably are not but just seems like x?.takeIf { it.name == "name" } ?.let { ... } with 2 lambdas, 5+ expression etc just cant be as clean as if( x!= null && x.name == "name" ) .. likewise expr?.let { it.dosometing } vs if( expr != null ) expr.doSometing() I know what the purpose is (wrt nullability guarentees and multiple evaluation points for expresions) but it just 'seems wrong'
s
yeah, at a glance I’d definitely call that over-kotlinized lol
there’s really nothing wrong with a simple
if
null-check every now and again
d
kneed a KWord for KoltinifiKation
Particularly unhappy with how paiinfully difficult it was to finally deduce (aka after atleast 10 hints/corrections/advise from someone who 'knew' and was so 'obvious' to that my density seemed unimangable) -- This tiny example from my 'bare minimal scripting' example: https://github.com/DALDEI/kotlin-script-sample
val compilation: ScriptCompilationConfiguration.Builder.() -> Unit = {
jvm {
// limit or extend classpath
// "mylib.jar","another.jar", wholeClasspath = imTooLazy
dependenciesFromCurrentContext( wholeClasspath = true)
}
}
There is NO WAY I could have ever deduced that expression/incantation from either docs, samples or soruce (of which I had all 3 AND personal assistance AND a year on off looking at it
THe irony being I know the intent is a clean and simple / obvious DSL -- and I suspect someday it might actually be one -- but -- in the current state its -- well I cant think of a word more torturous then torture 🙂
m
yeah, I agree with you that chaining
takeIf
and
let
in this case is not preferable to a simple if check... just sayin it's an option 🤷‍♂️