Hello, World! I'm having trouble with `is` return...
# javascript
b
Hello, World! I'm having trouble with
is
returning false when it should return true 😛 I'm using a
sealed class
for a state, which has a few `object`s and `data class`es as subclasses, and a
when
like so:
Copy code
when (state) {
    is Foo -> doSomethingFoo()
    is Bar -> doSomethingBar()
}
etc. Any suggestions?
more info: if I log
state::class
I do get
class Foo
or
class Bar
a
Does it work as expected in a test scenario such as the code you pasted? Actually making classes Foo and Bar to see if it works the way you expect. Without seeing the real code its hard to guess what the problem might be since it "should" work.
b
hmmm well I'll make a very simple test case then - be right back
(also I found this page, not sure if that means it's supposed to work or not -> https://kotlinlang.org/docs/reference/js-reflection.html )
this does work:
Copy code
sealed class State
object Loading:State()
object Success : State()
data class Error(val cause:String):State()

fun main(){
    val state:State = Loading
    logd("state=$state")
    when (state) {
        is Loading -> logd("Loading!")
        is Success -> logd("Success!")
        is Error -> logd("Error! ${state.cause}")
    }
}
so... it's weird 😞 I'll have to find the difference
a
the first 2 are objects which I'm not sure apply to "is" keyword
change to type class and see what happens
b
but it does work 🙂
in this simple sample. But the (almost) same code doesn't work in my "real" case
my problem may be related to the fact that I have two "windows" (this is actually for a Chrome extension)
I'll have a look at the generated Javascript and see if I understand what's going on
... well, after falling into a rabbit blackhole of js
typeof
and
instanceof
this random StackOverflow comment seems to explain my problem:
Copy code
instanceof works with objects in the same window. If you use iframe/frame or popup-windows each (i)frame/window have their own "function" object and instanceof will fail if you try to compare an object from another (i)frame/window. typeof will work in all cases since it returns the string "function".
a
I wonder if that is a kotlin js bug or its ambiguous and the programmer just needs to know this
the kotlin when statement could output different javascript that doesn't use instanceof but maybe there are cases where an alternative would be wrong
b
Ideally I would open an issue but it's kind of complicated to have simple repro steps.
a
sounds like the equivalent of having the “same” class loaded by two different class loaders in the JVM 😢
b
indeed it reminds me of it too. Would
is
work as expected in that case?