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

Sanendak

06/26/2021, 4:52 PM
Hello everyone! How to use property from object? Code in 🧵
👋 1
I have
Copy code
object ExampleObject {
    
    val objectInObject = object {
        val number = 1
    }
}
and I cannot get number. In example this not working
Copy code
val test = ExampleObject.objectInObject.number
a

Akshat Sharma

06/26/2021, 4:54 PM
Not sure this can help I created this object
Copy code
class GlobalVals {
    companion object {
        var numOfTimes: Int = 0
        fun incNumOfTimes(){
            numOfTimes = numOfTimes.inc()
        }
    }
}
Then i used them like this in main()
Copy code
GlobalVals.incNumOfTimes()
s

Sanendak

06/26/2021, 5:02 PM
Thanks, @Akshat Sharma! But this isn't the solution I'm looking for.
c

CLOVIS

06/26/2021, 5:13 PM
You can do:
Copy code
object ExampleObject {
  object ObjectInObject {
    val number = 1
  }
}
Why do you want to put objects inside objects?
👍 1
What's the error in your version?
s

Sanendak

06/26/2021, 5:24 PM
Yes, that's it! Thanks, @CLOVIS. I do this for nested navigation in my app
s

satyarth

06/27/2021, 7:32 AM
.
🚫 1
c

CLOVIS

06/27/2021, 7:34 AM
I don't think you can use () on an object, they are initialized implicitly
d

dmitriy.novozhilov

06/27/2021, 7:45 AM
@Sanendak In your original example you've created property
objectInObject
which was initiliazed by anonymous object. Since Anonymous object doesn't have any denotable name (actually it's name is
ExampleObject$objectInObject$1
), then compiler approximates type of
objectInObject
to its supertype (
Any
in this case), which obviously doesn't have property
number
c

CLOVIS

06/27/2021, 8:12 AM
I highly recommend you enable inlay type hints, that will make these cases much, much easier to understand @Sanendak: https://www.jetbrains.com/help/idea/inlay-hints.html
1
2 Views