https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
b

blakelee

09/18/2019, 5:38 PM
Does anyone else’s company not let them use !! anywhere, no exceptions?
l

looki

09/18/2019, 5:40 PM
Where would you need to use it? I always add
?: throw Exception("foo")
instead, so it's handled with a descriptive exception
6
b

blakelee

09/18/2019, 5:48 PM
For me it was interop with java classes that don’t have @NonNull annotations
var x: Int? = null
fun test(): Int {
    var y = x
    if (y == null) {
        y = someJavaFunctionThatDoesntReturnNull()
    }

    return 1 + y!!
}

fun someJavaFunctionThatDoesntReturnNull(): Int = 1
p

pavel

09/18/2019, 5:54 PM
fun test() = (x ?: someJavaFunctionThatDoesntReturnNull()) +1
b

blakelee

09/18/2019, 5:55 PM
That works too. But my use-case is more complex than that
v

Vlad

09/18/2019, 5:57 PM
!!
is a perfectly reasonable language feature. There is nothing wrong with it. Having a blanket ban on a language construct does not sound like a thought out decision
l

Lou Morda

09/18/2019, 6:10 PM
yes, my company does not let me. double bang is a big no no
m

Marko Mitic

09/18/2019, 6:14 PM
@Vlad so,
goto
is fine to use then? 😄
v

Vlad

09/18/2019, 6:18 PM
I don't think this is a fair comparison. There are lots of valid use cases for
!!
that don't bring it nowhere close to the issues usually attributed to goto
c

Colton Idle

09/18/2019, 6:25 PM
This seems like a terrible rule, but some people rather be in some super weird state instead of crash. There are reasons to use ?, !!, ?: etc. Having a ban seems unreasonable. There are definitely times where something should not be null and you don't want to propagate a null value. ? saves you from NPE, but will still propagate a null. Causing you to have weirdness or fail further down the line/further from the truth of the issue.
f

fred.deschenes

09/18/2019, 6:38 PM
I really don't get banning
!!
but allowing
?: throw...
s

streetsofboston

09/18/2019, 6:59 PM
Usually
!!
is a code smell, but sometimes it is not. Outright banning it makes no sense in my opinion. If you do, folks will do this `x ?: throw NullPointerException("...")`…. 🤷‍♂️
t

tddmonkey

09/18/2019, 7:20 PM
@Marko Mitic
goto
did have perfectly valid use cases in C 😄
j

Jukka Siivonen

09/18/2019, 7:53 PM
We use checkNotNull / requireNotNull which allows custom error message with more information of context if needed
1
l

Lou Morda

09/18/2019, 9:05 PM
I was actually told not to on the interview! I used them in my coding problem
w

wasyl

09/18/2019, 9:36 PM
I really don’t get banning
!!
but allowing
?: throw...
To me
!!
is typically
yeah it's null but I don't care
, while
?: throw
requires you to think why it could be null, and come up with appropriate message. And in case being not-null is an invariant then
checkNotNull
better conveys “I know it’s never null”. Similarly
requireNotNull
is appropriate to tell “This parameter should not be null so you messed up this invocation”. Anyway I don’t think I’ve seen legitimate usage of
!!
other than being lazy and not wanting to provide message/refactor code a bit. It’s mostly people doing
if (field != null) field!!.doSomething()
too, so I also get why it’s difficult for some to see why it’d be useful. I wonder if Kotlin would have
!!
operator if it wasn’t for Java interop
1
👍 2
p

pavel

09/18/2019, 9:39 PM
I looked through my code and found this:
val foo:Int = listOf(fooService.getFoo(), barService.getBar(), bazService.getBaz()).max()!!
the list will never be empty and it’s obvious that it isn’t to any reader
w

wasyl

09/18/2019, 9:53 PM
🤔 I agree this looks like a reasonable usage of
!!
. Personally I’d still write ``listOf(…).max().let(::checkNotNull)` but I guess this just proves the point that some people just don’t like
!!
🙂 Anyway I think forbidding
!!
also serves junior developers, since typically having to use it means there’s something iffy with your code (like the field I mentioned before)
p

pavel

09/18/2019, 9:59 PM
I completely agree that usually,
!!
can be expressed better in other ways. And having a general rule against that operator is a good idea. But, this rule, just like most other rules, has exceptions
👍 1
g

gildor

09/19/2019, 12:04 AM
Hmm, but why do you need listOf().max() in this case? Why not
maxOf
function
p

pavel

09/19/2019, 12:16 AM
In this particular case, yes. But of I had 4 things or 5?
y

yen

09/19/2019, 12:57 AM
The point is that there are cases (e.g. calling
max()
on a list that is never empty) where you the programmer knows that some thing cannot be null, but the compiler can’t prove it
Cases like these are where things like
!!
becomes necessary
I really like the
?: throw Exception(...)
solution for cases like these
g

gildor

09/19/2019, 1:31 AM
also
?: error(...)
In this particular case, yes. But of I had 4 things or 5?
Create function
maxOf
with vararg argument. I actually surprised that its’ not there In general it looks as a good example when “I know it’s not null, give me my double bang” should be replaced with more efficient and much more idiomatic function (from stdlib or your own) Even super simple extension like
maxOrThrow()
would be better because provides much better error message
But I want to be clear, I’m not for any restrictions in code style about this, or of language, I’m just trying to say that many cases it’s actually good recommendation, to wait a second and ask yourself “can I improve it by avoiding nullability or at least by providing some meaningful error message”, actually investigate such KotlinNullPointerExceptions is not so easy in many cases because you not always have context, sometimes they are caused by Java interop and line where it crashed not always enough Also in my career I saw too many “ImpossibleExceptions” on prod
s

Stephan Schroeder

09/19/2019, 12:15 PM
I’m pretty sure this works:
fun test(): Int {
    val y:Int = x ?: someJavaFunctionThatDoesntReturnNull()
    return 1 + y
}
Can’t you always assign a platform type to a non-nullable type, as long as you make the type of the variable explicit!?!
g

gildor

09/19/2019, 11:26 PM
Yes, but it works only for Java types and only if those types are not annotated with Nullability annotations
👍🏼 1
c

Colton Idle

09/20/2019, 3:33 AM
@gildor
also
?: error(...)
I'm unfamiliar with that. What's error()?
g

gildor

09/20/2019, 5:22 AM
@Colton Idle This is a function from standard library (also in package
kotlin
so doesn’t require import: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/error.html
c

Colton Idle

09/25/2019, 1:47 PM
@gildor that's really helpful. It's like a quick way to create a IllegalStateException with a message. 👍 TIL