https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
s

stantronic

09/06/2022, 11:49 AM
Is there any reason that Kotlin allows for inner classes, but not inner objects?
3
s

spand

09/06/2022, 11:57 AM
objects are singletons hence it doesnt really make sense for it to be inner
s

Sam

09/06/2022, 11:58 AM
Really this is an inner object:
Copy code
class Outer {
    val X = object { ... }
}
So the question isn’t so much how to do it, but why you can’t do it with the syntax
Copy code
class Outer {
    inner object X { ... }
}
I think probably the reason is just that the latter syntax is redundant to the former, but I don’t have any evidence for that claim 🤷
s

stantronic

09/06/2022, 12:07 PM
the anonymous object syntax behaves differently though - e.g.
Copy code
class Outer {
 val X = object {
   val prop = "stringProp"
 }

 fun printIt() {
   print(X.prop) // this will be a compiler error
 }
}
😢 1
whereas
Copy code
class Outer {
  inner class Inner {
    val prop = "stringProp"
  }
  val X = Inner()

  fun printIt(){
    print(X.prop) // fine
  }
}
s

Sam

09/06/2022, 12:13 PM
the anonymous object syntax behaves differently though
that’s a good point, it’s definitely a serious limitation that hadn’t initially occurred to me. I can see why an
inner object
would be strictly more useful than an object expression, because it would create a type as well as an instance
s

stantronic

09/06/2022, 12:15 PM
Copy code
yeah, thats what i would like - makes it much more useful imo, and yet limits the creation to one per instance of the outer class.
4 Views