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
hiring-french
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
m

Manuel Dossinger

10/13/2021, 7:54 PM
Hey. I can do `my?.chained?.call?.of?.operators?`and get null, if any of these is null. Is there a nice way of achieving the same for parameters? e.g.
fun foo(a: Type1, b: Type2, c: Type3): Type4

val result: Type4? = foo(myA?, myB?, myC?) // is null if any of the parameters is null
g

Grégory Lureau

10/13/2021, 7:58 PM
There is a Jetbrains annotation to define a contract on a function if that's what you need
@Contract("null, null, null -> null") fun foo(...)
m

Manuel Dossinger

10/13/2021, 8:01 PM
That seems to be the opposite of what I want 🙂 I want to leave the function alone, and just want to have syntactic suger for the caller.
e

ephemient

10/13/2021, 8:01 PM
at the moment, you can do something like
val result = if (myA != null && myB != null && myC != null) {
    foo(myA, myB, myC)
} else null
val result = run {
    foo(myA ?: return@run null, myB ?: return@run null, myC ?: return@run null)
}
👍 1
g

Grégory Lureau

10/13/2021, 8:01 PM
Did you mean to avoid calling the
foo
method completely? Looks weird to me, the nullability of args as nothing to do with calling the method, even if I suppose there is some cases where you would want to do that. Also you could do a weird
?.let
embedded checks or just a simple
if (mA!= null && myB != null..)
e

ephemient

10/13/2021, 8:01 PM
there's also some Arrow monad thing
in the future, perhaps https://youtrack.jetbrains.com/issue/KT-45862
👌 1
👍 1
c

Casey Brooks

10/13/2021, 8:02 PM
The first thing that comes to mind is to pass the params into a list, and then use something like
.any { it == null }
. An easier-to-understand solution might just be to use precondition checks at the start of the function on each parameter
fun foo(a: Type1?, b: Type2?, c: Type3?): Type4? { 
    if(a == null) return null
    if(b == null) return null
    if(c == null) return null
    
    // at this point, all parameters have been smart-cast to non-null
    return Type4(a.toString() + b.toString() + c.toString())
}
m

Manuel Dossinger

10/13/2021, 8:10 PM
Ok, then I'll hope for the Future. @Casey Brooks, I was also considering the list + any idea, but that seems to be unnecessary overhead. And the second suggestion has the drawback, that the method itself needs to deal with the null-logic.
thanks for the input everyone!
t

Tobias Suchalla

10/14/2021, 6:33 AM
You could also write a wrapper function (or multiple for more/fewer parameters):
fun <P1, P2, P3, R> runOrNull(
    param1: P1?, 
    param2: P2?, 
    param3: P3?, 
    block: (P1, P2, P3) -> R
): R? {
    return block(
        param1 ?: return null,
        param2 ?: return null,
        param3 ?: return null
    )
}

fun foo(a: Type1, b: Type2, c: Type3): Type4

val result: Type4? = runOrNull(myA, myB, myC, ::foo)
e

ephemient

10/14/2021, 6:39 AM
more
let
-like than
run
-like and would make sense to
inline
but yeah, things of that nature have been thrown around before (e.g. https://github.com/stupacki/MultiFunctions)
unfortunately you can't varargs it without losing type information