https://kotlinlang.org logo
#announcements
Title
# announcements
j

Juanoterocas

09/09/2019, 10:14 PM
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

Dominaezzz

09/09/2019, 10:16 PM
That should be copy-paste compatible with kotlin.
s

Shawn

09/09/2019, 10:19 PM
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

Juanoterocas

09/09/2019, 10:27 PM
now is working, thanks for your help
m

Matt Thompson

09/09/2019, 11:40 PM
you might also consider
takeIf
-
x?.takeIf { it.name == "name" }?.let { ... }
👎 1
d

DALDEI

09/10/2019, 1:40 AM
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

Shawn

09/10/2019, 1:40 AM
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

DALDEI

09/10/2019, 1:44 AM
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

Matt Thompson

09/10/2019, 2:29 PM
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 🤷‍♂️