Is this the correct behavior? Only is working insi...
# getting-started
j
Is this the correct behavior? Only is working inside functions
c
Running code outside of functions is not allowed.
The only things you can do are function / class declarations.
However, this is allowed:
Copy code
object Hello {
  val x = "Hello"
}

fun main() {
  Hello.x // whatever
}
r
It's not about code outside of functions. It works the same when you put
hello.x
inside
main()
. It's strange for me as well.
c
Ah, then there's a second problem, but I won't just give the answer to it. What's the type of the
hello
variable?
r
It's
Any
in the second case and
<anonymous object : Any>
in the first (working) one.
But it's for sure not clear for me šŸ˜‰
j
that is a scratch file, I can run code there @CLOVIS
Same here
c
Yep, the variable's type is
Any
, and
Any
doesn't have an
x
attribute.
The version I wrote above will work, because I'm actually declaring a new type (with an
x
attribute)
j
image.png
image.png
c
Enable type hints to understand these cases better
j
image.png
image.png
well, my use case is to have it public, so it isn't working for me so, but I would like compiler could resolve it even if it is public..
c
Check the version I sent, it will work no matter if it's public or not.
j
I know that works, but I want trying to avoid that, having an unnecessary public object in the namespace
but I have to use that
@Robert Jaros yep, here:
When an anonymous object is used as a type of a local orĀ privateĀ but notĀ inlineĀ declaration (function or property), all its members are accessible via this function or property
c
You want to: ā€¢ provide the caller with an object that has an x attribute that they can use ā€¢ not declare the object You can't have both
j
yeah, thank you šŸ˜›
t
just as a sidenote: you could also make your anonymous object implement an interface. But as long as that interface isn't used anywhere else, you don't gain much from that
šŸ‘ 1