Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my nested class not accessible? (Kotlin)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading