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
d

dalexander

10/01/2019, 2:24 PM
I just ran into a seeming shortcoming in the type inference system, can't find any tickets on youtrack, has anyone else run in to this?
// both Foo and Bar extend Item
val item: Any? = getSomething()
if(item is Foo || item is Bar) {
  // I would expect this to smart cast to Item -- defining Item as a sealed class doesn't seem to help either
  doThingWithItem(item) //Error - Type mismatch, required: Item, found Any?
}
d

diesieben07

10/01/2019, 2:26 PM
That's not how smart casts work. Smart casts will only cast to types you explicitly checked for.
s

Shawn

10/01/2019, 2:28 PM
also, why not just check if
item is Item
?
unless, I guess, you only want to perform an action if type of the object is one of those two subclasses
still, maybe kind of a smell ¯\_(ツ)_/¯
d

dalexander

10/01/2019, 2:30 PM
Because I believe there are cases where I don't want to call
doThingWithItem()
with any Item subclass (I'm actually going to check though-- this line came about during a Java -> Kotlin conversion).
I am not a fan of doing type checking myself if I can avoid it.
r

Ruckus

10/01/2019, 2:32 PM
@dalexander Could you elaborate on that?
if(item is Foo || item is Bar)
is type checking. Do you mean you don't like casting if you can avoid it?
d

dalexander

10/01/2019, 2:32 PM
Yeah, definitely there are kinds of
Items
that should be excluded from that call.
d

diesieben07

10/01/2019, 2:32 PM
The reason this doesn't work is to prevent "spooky action at a distance" situations. If you were to add additional subclasses of
Item
suddenly your smart-cast no longer compiles (even worse, it's in a seperately compiled library and is now incorrect!)
g

gian

10/01/2019, 2:33 PM
If you add additional sublasses, still Foo and Bar respond to Item, where is the problem?
d

dalexander

10/01/2019, 2:33 PM
That's not true. Adding new subclasses of
Item
doesn't mean if something is a
Foo
or
Bar
that it is also no longer an
Item
.
d

diesieben07

10/01/2019, 2:34 PM
Yes I misspoke there, what I described was a different situation. However there are still situations where this breaks (e.g. the superclass is changed)
My original point still stands: Kotlin will only smart-cast to types that you explicitly checked for
No implicit handling is done
d

dalexander

10/01/2019, 2:34 PM
It seems like it's just a limitation of smart casting, which I think is a fine answer. The follow up question is if the Kotlin teams want to consider this use case.
g

gian

10/01/2019, 2:34 PM
abstract class Parent
class Child1 : Parent()

fun main() {
    val a: Any? = ""
    if (a is Child1)
        funOnParent(a)
}

fun funOnParent(parent: Parent) = println(parent.javaClass)
This is working for me
d

dalexander

10/01/2019, 2:35 PM
Okay, so if I change the if statement to
if(item is Foo) {
        doThingWithItem(item)
    }
it works by the way.
d

diesieben07

10/01/2019, 2:35 PM
Yes, because then you get a smart-cast to
Foo
.
g

gian

10/01/2019, 2:36 PM
So basically with more than one the compiler is still unsure on the exact type, even though both are children of
Item
d

diesieben07

10/01/2019, 2:37 PM
You can't smart-cast to two separate types. Kotlin does not have union types
d

dalexander

10/01/2019, 2:37 PM
Right-- presumably because it doesn't have internal representations for this kind of composite type. Which is fine.
k

Kroppeb

10/01/2019, 3:48 PM
mmh. I feel like these should be equivalent no?
if(item is Foo || item is Bar) {
  doThingWithItem(item)
}
if(item is Foo) {
  doThingWithItem(item)
} elseif(item is Bar){
  doThingWithItem(item)
}
and
when(item) {
  is Foo -> doThingWithItem(item)
  is Bar -> doThingWithItem(item)
}
🇳🇴 1
interface Item

class Foo:Item
class Bar:Item

fun getValue(): Any? = TODO()

fun main(){
	// a:Any
	val a = getValue().let{if(it is Foo || it is Bar) it else TODO()}

	// b:Item
	val b = when(val t = getValue()){
		is Foo -> t
		is Bar -> t
		else -> TODO()
	}

	// c:Item
	val c = getValue().let{if(it is Foo) it else (if(it is Bar) it else TODO())}
}
m

mikhail.zarechenskiy

10/01/2019, 4:09 PM
Right, we don't have union types inside the compiler but using common supertype of
Foo
and
Bar
after a check like
item is Foo || item is Bar
for
item
can be a good approximation. I think it can be a nice feature, @dalexander can you please create a YT ticket?
👍 1
d

dalexander

10/01/2019, 4:16 PM
Sure, I can see about putting together a use case and a ticket.