https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Javier

09/20/2021, 10:14 AM
Is this the correct behavior? Only is working inside functions
c

CLOVIS

09/20/2021, 10:21 AM
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

Robert Jaros

09/20/2021, 10:23 AM
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

CLOVIS

09/20/2021, 10:25 AM
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

Robert Jaros

09/20/2021, 10:26 AM
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

Javier

09/20/2021, 10:45 AM
that is a scratch file, I can run code there @CLOVIS
Same here
c

CLOVIS

09/20/2021, 10:46 AM
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

Javier

09/20/2021, 10:47 AM
image.png
image.png
c

CLOVIS

09/20/2021, 10:47 AM
Enable type hints to understand these cases better
j

Javier

09/20/2021, 10:48 AM
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

CLOVIS

09/20/2021, 10:49 AM
Check the version I sent, it will work no matter if it's public or not.
j

Javier

09/20/2021, 10:50 AM
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

CLOVIS

09/20/2021, 10:50 AM
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

Javier

09/20/2021, 11:32 AM
yeah, thank you 😛
t

Tobias Berger

09/20/2021, 3:09 PM
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