I was trying to follow an example from the nested classes documentation: Kotlin docs - Nested and inner classes
So I tried:
fun main(){
var tester = Test()
println(tester.x) // 42
tester.Foo().bar() // compiler error - unresolved reference: Foo!!!
}
class Test {
var x:Int = 42
class Foo {
fun bar() = println("foobar!")
}
}
However, the nested class was not accessible. I'm obviously missing something really obvious.
CodePudding user response:
If you're not trying to create an inner class, then a nested class should be referenced like so:
fun main() {
var tester = Test()
println(tester.x) // 42
// Static reference
Test.Foo().bar() // foobar!
}
class Test {
var x:Int = 42
inner class Foo {
fun bar() = println("foobar!")
}
}
As @broot said in his comment:
Nested classes are static, so you don't create them from instances