#? and !! in kotlin
1 messages · Page 1 of 1 (latest)
<@&1008423204219531294> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
google "kotlin null safety", they have a good official tutorial on it
This makes more sense, i tried (? And !! In kotlin)
essentially, !! the double-bang means
"if its null, throw" and makes a possibly nullable type into a non nullable
Foo is non nullable
Foo? is nullable
foo?.bar()
means "call bar() only if foo is not null"
Can i get an example please
Ye i get this one now,
foo ?: bar
means "use foo, if its null, use bar instead", called the elvis operator
Kotlin's docs are pretty good with this stuff, BTW
Like foo ?: bar.length and (foo) and (bar) are variables?
ssure:
val pet: Pet? = john.getPet()
pet!!.bark()
references yes
above example gets johns pet. but thats nullable, John might not have a pet
but then we do!! on it. so we require that pet exists (if it doesn't, it throws)
so after doing that, pet is known to be non nullable
val maybePet: Pet? =...
val definitelyPet: Pet = maybePet!!
its all just shorthands for a bunch of null checks
Ok so "?" Is for declaring/assigning and "!!" For methods?
Foo? is a nullable type
foo?.bar()
calls methods only if its not null
called safe-access
foo ?: bar
is if-else
the elvis operator
And doesn't "!!" Do the same?
no
!! throws an exception. it requires that its not null
?. is "only do it if not null, otherwise don't do anything"
Yeah now i get it, i think
the kotlin docs have great examples on this
id suggest u read it first
it answers all questions
For example here u used "!!" But where is the exception?
if john has no pet, this code crashes when executed
with
pet?.bark()
it doesn't crash and simply doesn't bark
it also has the kotlin playground. so u can try it out and execute right there on the website
Do you know java optionals?
?: is like Optional#orElse
?. Is like Optional#map or Optional#ifPresent depending on the usage
And !! Is like Optional#orElseThrow
This can also be used as Optional#flatMap
Basically kotlin has Javas Optional API bundled into its syntax
For compulsory null safety
also if somehere here knows spigotapi i would use some help
we have a minecraft category when u ask a question here
there are people who can help
not too many, but some
u just gotta ask a question and select minecraft 🙂
oh cool