Icon

The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Skip to end of metadata
Go to start of metadata
Icon

The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Classes can be nested in other classes:

class Outer() { 
  private val bar : Int = 1 
  class Nested() { 
    fun foo() = 2 
  } 
} 
 
val demo = Outer.Inner().foo() // == 2

Inner classes

A class may be marked as inner to be able to access members of outer class. Inner classes carry a reference to an object of an outer class:

class Outer() { 
  private val bar : Int = 1 
  inner class Inner() { 
    fun foo() = bar 
  } 
} 
 
val demo = Outer().Inner().foo() // == 1

See Qualified this expressions to learn about disambiguation of this in inner classes.

What's next

  • No labels

12 Comments

  1. Are there static inner classes?

    1. You'll need to place inner class inside class object like:

      class Outer [ 
        class object { 
          class Inner() {} 
        } 
      }
      1. What's the different between "static inner class" and "nested class" ?

        1. Strictly speaking, "static inner class" is an oxymoron, a Java class can be either static or inner. Colloquially, "static inner class" refers to a nested class.

  2. tried to run "inner" class example, but got following exception.

      1. that's weird. I can run the code from a main method, without any issue. but running it from following test method, causing above exception

        1. Could you send me a project this problem reproduces in? Thanks

          1. You can find the project here: https://dl.dropboxusercontent.com/u/35706523/inner-class.zip

            Unit test is failing but main method can be run successfully. 

            1. Sorry for the delay. It's a bug in the compiler. I entered it in YouTrack on your behalf: http://youtrack.jetbrains.com/issue/KT-3847

  3. Does Kotlin have inner objects ? Would it be usefull ? like in 

    class A{ 
     
    var process:Int = 0 
     
    object handler : Handler() { 
     
     final override fun handleMessage(msg: Message) { 
     
       if (msg.what == process) doSomethingwithClassAInstance() 
     
     } 
     
     
    }

    This seems to work ATM :

    val handler = object :  Handler() { 
            final override fun handleMessage(msg: Message) { 
                super<Handler>.handleMessage(msg) 
                if (msg.what != this@LibraryAdapter.process) { 
                    
                } 
            } 
        }
    1. Kotlin does not have inner objects, only nested ones, i.e. object declarations are always singletons, thus they can not have references to outer instance. The workaround that you mention is the best one I know of.