Is there a technical reason why `@JsStatic` cannot...
# javascript
m
Is there a technical reason why
@JsStatic
cannot be applied to members of of non-companion obvious, when this pattern works just fine with
@JvmStatic
? To be fair this limitation is mentioned in the associated KDoc comment, but it would be nice if the behaviour was consistent with
@JvmStatic
.
e
You mean "non-companion objects"? So like:
Copy code
object Example {
  fun myFun() {}
}
t
@Artem Kobzar ^^
m
Yep, exactly. Just top level object declarations.
e
I was looking at the compiled JS code, and honestly I think a
@JsStatic
on object members should work just fine, as it does with companion ones.
Unless there is a limitation that I'm naively missing.
m
Trying causes the error
Only members of class companion objects can be annotated with '@JsStatic'.
for me.
e
Ah yes, I meant that I don't see why the compiler shouldn't support it.
At the end of the day an object with
@JsStatic
could compile to (taking my previous example):
Copy code
function myFun() {
    return getExampleInstance().myFun();
}

class Example {
    myFun() {
        return "two"
    }
}

var example;

function getExampleInstance() {
    if (!example) {
        example = new Example();
    }
    return example;
}

Example.myFun = myFun;

console.log(Example.myFun())
console.log(new Example().myFun())
a
@Marc could you please create a ticket with a description of your use-case (basically, what you're trying to solve with @JsStatic on non-companion members). I believe we can support it, but it would be nice to know what kind of pattern is applied with such usage of @JsStatic
m
If you phrase it like that, I am not sure if what I am doing is even correct 😄 I am just using the objects to basically namespace static functions and constants in a way that works the same across Java, Kotlin and JS.
But I can create the ticket anyway. I think supporting it would be good if just to make both
xxxStatic
annotations behave consistently.
a
Sure, thank you 🙏
e
I believe the use case is simply skipping the
getInstance()
call.
👀 1
👍 1
a
And you are definitely doing everything correct. I just need to know different specifics to keep them in mind while we are working on the
companion block
feature pepenotingfast
m
I didn't know about that new proposal. I read through the KEEP discussion and it seems like several other people brought up the issue of organising static elements, which from what I can see is not getting immediately addressed (meaning top level objects will stay the preferred solution at least until something like a
namespace
is introduced). Then I think it makes sense to fix the current interaction with objects.
thank you color 1
➕ 1