Is there any reason that Kotlin allows for inner c...
# language-proposals
s
Is there any reason that Kotlin allows for inner classes, but not inner objects?
3
s
objects are singletons hence it doesnt really make sense for it to be inner
s
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
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
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
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.