Skip to end of metadata
Go to start of metadata

Classes and Primary constructors

Here is an example of a class declaration in Kotlin:

class Example(param : Int) { 
  val property = param 

Let's start with the header that says

class Example(param : Int) {

This is a declaration of a class Example that has a constructor that takes one parameter of type Int. Such constructors, declared immediately in the class header, are called primary constructors.

To create a new instance of the class Example, one simply calls its constructor, as if it were a regular function:

val e = Example(10)

(Note that one does not need the new keyword.)

What does the primary constructor do? It executes the initializers of properties, in the order of declaration. These initializers can use the constructor's parameters. In the example above, the only thing the constructor does is initialization of property.

Additionally, one can place "anonymous initializers" in the body of a class, just surrounding pieces of code with curly braces:

class ExampleWithAnonymousInitializer(param : Int) { 
  val property = HashSet<Int>(); 

Here, the primary constructor first creates a new HashSet, assigns it to property and then adds the value of param to this set.

Parameters of primary constructors can be prefixed with val or var keywords to declare corresponding properties in-place:

class Bean(val prop1 : Int, val prop2 : String)

Class body is optional, and the example above is a complete declaration of a class that has two properties prop1 and prop2 and a primary constructor with two parameters, that initializes these properties in an obvious way.

So, it does not take you much code to declare a bean-style data class in Kotlin, at least it is a lot less code than in Java.

Class members

Classes have the following kinds of members:


All classes in Kotlin have a common superclass Any, that is a default super for a class with no supertypes declared:

class Example // Implicitly inherits from Any

Any is not java.lang.Object; in particular, it does not have any members, not even equals(), hashCode or toString(). This does not mean that you can not call, say, toString() on any object: you can, but it will be an extension function. See Java interoperability#Object methods for more details.

To declare an explicit supertype, one puts it after a colon in the class header:

open class Base(p : Int) 
class Derived(p : Int) : Base(p)

As you can see, the base type can (and must) be initialized right there, using the parameters of the primary constructor.

The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Item 17 of Effective Java: Design and document for inheritance or else prohibit it.

A class may have many supertypes. See this post for more details.

Overriding members

As we mentioned before, we stick to making things explicit in Kotlin. And unlike Java, Kotlin requires explicit annotations for overridable members that we call open and for overrides:

open class Base { 
  open fun v() {} 
  fun nv() {} 
class Derived() : Base() { 
  override fun v() {} 

The override annotation is required for Derived.v(). If it were missing, the compiler would complain. If there is no open annotation on a function, like Base.nv(), declaring a method with the same signature in a subclass is illegal, either with override or without it. In a final class (e.g. a class with no open annotation), open members are prohibited.

A member marked override is itself open, i.e. it may be overridden in subclasses. If you want to prohibit re-overriding, use final:

open class AnotherDerived() : Base() { 
  final override fun v() {} 

Wait! How will I hack my libraries now?!

One issue with our approach to overriding (classes and members final by default) is that it would be difficult to subclass something inside the libraries you use to override some method that was not intended for overriding by the library designer, and introduce some nasty hack there.

We think that this is not a disadvantage, for the following reasons:

  1. Best practices say that you should not allow these hacks anyway
  2. People successfully use other languages (C++, C#) that have similar approach
  3. If people really want to hack, there still are ways: in some cases it will be possible to write your hack in Java, and Aspect frameworks always work for these purposes...


Traits are essentially interfaces with (optional) method bodies. See this post for more details.

Overriding rules

In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits many implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation (perhaps, using one of the inherited ones). To denote the supertype from which the inherited implementation is taken, we use this qualified by the supertype name in angle brackets, e.g. this<Base>:

open class A { 
  open fun f() { print("A") } 
  fun a() { print("a") } 
trait B { 
  fun f() { print("B") } // trait members are 'open' by default 
  fun b() { print("b") } 
class C() : A(), B { 
  // The compiler requires f() to be overridden: 
  override fun f() { 
    super<A>.f() // call to A.f() 
    super<B>.f() // call to B.f() 

It's fine to inherit from both A and B, and we have no problems with a() and b() since C inherits only one implementation of each of these functions. But for f() we have two implementations inherited by C, and this we have to override f() in C and provide our own implementation that eliminates the ambiguity.

Abstract classes

As in Java, a class and some of its members may be declared abstract. An abstract member does not have an implementation in its class. Thus, when some descendant inherits an abstract member, it does not count as an implementation:

abstract class A { 
  abstract fun f() 
trait B { 
  open fun f() { print("B") } 
class C() : A(), B { 
  // We are not required to override f() 

Note that we do not need to annotate an abstract class open – it goes without saying. Neither need we annotate an abstract function open.

One can override a non-abstract open member with an abstract one:

open class Base { 
  open fun f() {} 
abstract class Derived : Base() { 
  override abstract fun f() 

Overridable properties and accessors

A property may be declared open as well as a function. This actually means that accessors of this property can be overridden:

open class Base { 
  open val p : Int 
    get() = 1 
class Derived : Base() { 
  override val p : Int 
    get() = 2 


The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code. A class Derived can inherit from a trait Base and delegate all of its public methods to a specified object:

trait Base { 
  fun print() 
class BaseImpl(val x : Int) : Base { 
  override fun print() { print(x) } 
class Derived(b : Base) : Base by b 
fun main() { 
  val b = BaseImpl(10) 
  Derived(b).print() // prints 10 

The by-clause in the supertype list for Derived indicates that b will be stored internally in objects of Derived and the compiler will generate all the methods of Base that forward to b.

Generic classes

See Generics

Class objects

In Kotlin, unlike Java, classes do not have static methods. In most cases, namespace-level functions form a good substitute for them, but there are a few cases when they don't. These cases involve access to class' internals (private members).

For example, to replace a constructor with a Factory method, one makes the constructor private and provides a function that calls the constructor. But if this function in located outside the class in question, it would not have any access to the constructor.

To address this issue (and to provide some other interesting features), Kotlin introduces a concept of a class object (the closest analog in other languages would be Companion objects in Scala). Roughly speaking, a class object for class C is an object (in the sense of Object declaration) that is associated to C. There may be not more than one class object for each class. A class object is declared inside its associated class, and thus it can access its private members. A class object for C itself is (usually) not and instance of C. For example:

class C() { 
  class object { 
    fun create() = C() 
fun main() { 
  val c = C.create() // C denotes the class object here 

At first you may think that this is just a way of grouping static members of a class together instead of mixing them with instance members: in Java we access static members of C by calling, and the same happens with class object's members in Kotlin. But in fact there is an important difference: a class object can have supertypes, and C, as an expression denotes this object as a value, so one can pass it around, say, as an argument for a function. Let's modify our example to demonstrate this:

abstract class Factory<out T> { 
  abstract fun create() : T 
open class C() { 
  class object : Factory<C>() { 
    override fun create() : C = C() 
fun main() { 
  val factory = C // C denotes the class object 
  val c = factory.create() 
Class object bounds are not supported yet
See the corresponding issue.

Note that class objects are never inherited:

class D : C() 
val d = 
.create() // Error: no class object for D

A description of some more interesting features related to class objects can be found in the Generic constaints section.

Note: if you think that class objects are a great way of implementing singletons in Kotlin, please see Object expressions and Declarations.

Best practices related to this feature

Effective Java Second Edition by Joshua Bloch
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Item 18: Prefer interfaces to abstract classes

Similar features in other languages

IDEs automatically generate delegating methods.

Project Lombok implements delegation in Java with annotations.

Scala has traits.

Groovy has Categories and Mixins.

What's next

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Jul 20, 2011


    A member marked override is itself virtual, i.e. it may be overridden in subclasses. If you want to prohibit re-overriding, use final

    Any thoughts on reversing this and making overridden members final unless annotated with open?  Seems more consistent and may allow you to remove final as a keyword from the language

    1. Jul 21, 2011

      It's a matter the tradeoff between brevity and explicitness, and we are not exactly sure how it turns out in the end. We plan to write some
      real code in Kotlin, and then actually settle on the defaults.

      We intend to keep final even if it's default everywhere, because it's good to be able to explicitly write what you want (Java's "package-local" access modifier is a good lesson for us), and it's not a keyword anyway, just an annotation.

      1. Jul 23, 2011


        How about using 'open' instead of 'virtual' for non-final methods? It seems more consistent that way. I don't see the need for the separate 'virtual' keyword.

        1. Jul 27, 2011

          Makes sense. Thank you

  2. Jul 20, 2011


    I didn't see any examples on overloading functions/methods (other than operator overloading).  Is this feature present?  Personally I think overloading makes things more complex.  I'd rather see optional params w/ default values and no overloading.

    1. Jul 21, 2011

      Overloading is supported. This is backed by a few reasons. First of all, we want to be able to call Java code, and it has overloads, and then, some of the overloads are not just emulating default parameters (consider constructors that take data from different sources).

      1. Jul 21, 2011


        No overloading is a huge win, as Fantom has shown. Fantom also shows how to handle constructors, using limited overloading. Just because Java has overloads and you allow calling of Java code isn't sufficient reason to allow overloading in Kotlin itself.

        1. Jul 21, 2011

          Yes, it is a huge win.

          But we have to be able to resolve overloads from existing libraries, and I don't see how we could do it without having overloads in the language.

          1. Jul 21, 2011


            What if overloading was just a language interop feature and not something allowed in actual Kotlin code?  I'm trying to think how this could work.  Any ideas anyone?

            1. Jul 25, 2011


              In my opinion, function overloading is an important feature and I don't want to miss it.

            2. Jul 26, 2011

              Overloading is very nice when all variants have just one parameter.
              This is for this reason that we want operator overloading right?
              They are annoying to write just to emulate optional parameters, but we dont bother with that when we have a language with default arguments (like Kotlin).

              For the other gray zones, I think it would be better to let programmers make their own decision.
              We want a language without bloat, not a dictatorship.
              I guess that this "huge win" would be simplifications inside the guts of the compiler and to the reflection api.
              In terms of performance, my basic java bytecode understanding says there is nothing to gain by killing overloading.

  3. Jul 22, 2011


    I like the open annotation very much. I saw many people overusing and misusing inheritance, maybe this will change this habit.

  4. Jul 22, 2011

    Please differentiate more strongly between multiple inheritance and mixins.  Kotlin seems from the description to be a multiple inheritance language rather than a mixin one.  (For the benefit of readers not familiar with the difference -

    I'm happy with Kotlin either way, just want more clarity in the documentation on this point.  (And thank you for having this feature.)

    Question: with multiple inheritance how will this appear to Java when constructing diamond-inheritance objects, order of construction, avoiding multiple instances of base class, etc.?  How will it look to Java reflection?

    UPDATE: I found some answers to my MI question on the 2nd set of slides from the JVM lang summit -;

    1. Jul 25, 2011


      Please differentiate more strongly between multiple inheritance and mixins.  Kotlin seems from the description to be a multiple inheritance language rather than a mixin one.  (For the benefit of readers not familiar with the difference -

      I'm happy with Kotlin either way, just want more clarity in the documentation on this point.  (And thank you for having this feature.)

      Seconded. If they are truly mixins, they're not supposed to be instantiated.

      And if we are on this way, why not go for the full extent of inheritance, such as MI à la Eiffel or traits à la Self? Such a mix (pun intended) of the two approaches would allow for (automagic) delegation (composition) as well as (multiple) inheritance, with renaming or removal of inherited/composed features. (Except that removal of inherited features breaks subtyping, and hence is bad for the static typing of your code. So maybe it's not such a great idea.)

      Maybe fortunately, I do not have any suggestion as for the syntax that would implement all of that, but I have the feeling that it might require quite a bit of boilerplate...

  5. Jul 24, 2011


    Isn't there an error in the factory example? Since member functions are final by default, the create method in the abstract factory class should need an "abstract" annotation.

    1. Jul 25, 2011

      In an abstract class any function that doesn't have a body considered abstract

  6. Jul 25, 2011


    About delegation.

    How your example is any different from regular old implementation inheritance without any "as", which it is supposed to be a replacement of?

    And the  wikipedia page you're linking to presents delegation as implemented by composition/aggregation, not inheritance.

    Here is how I would see effective automagic delegation:

    1. Jul 25, 2011

      Yeah, this is kind of works this way too, see syntax corrections to class C

      class C() : I by i { // we either delegate to an I instance passed via constructor parameters or to our own property 
        val i : I = A(); 
        // normal attributes 
        fun toA() { i = A() } 
        fun toB() { i = B() } 
  7. Jul 25, 2011


    A bit of nitpicking about the syntax for multiple implementation inheritance.

    It is a bit grating to me; reusing the "<>" which usually denote generics in a context where nothing is related to genericity (abstract type parameters) seems a bit a of mistake. Even if it's known as the infamous "diamond operator", it would be too much of a pun to justify its use.

    Wouldn't it be possible to come up with a different syntax? Maybe something along the lines of "A.f(); B.f()".

    1. Jul 25, 2011

      In A.f() A denotes "class A"'s class object instance expression.

      1. Jul 26, 2011

        super@A.f() would fit well with what we have at This expressions
        Is the diamond for that use case inspired by another language?

        1. Jul 27, 2011

          I agree that the diamond there is not the best idea. We'll think of something better. @A is a little different, for labels are used for lexical scopes...

  8. Jul 27, 2011


    I have a suggestion for the multiple inheritance implementation. As I understood from the page, there still could be problems. Please, take a look here: (in russian)

    What do you think of the CZ's approach?


    1. Sep 06, 2011

      Thanks for your suggestion. See this blog post for the reply:

      1. Sep 08, 2011

        Andrey, thank you. This blog post is thoughtful and deep and opens a lot of nontrivial questions to analyze.

        1. Sep 08, 2011

          Thanks for your kind words.

  9. Jul 29, 2011


    What happens in this situation?

    How meny copy of A will be contains in D?

    In other words, how you solve the initialization problem? 

    1. Jul 29, 2011

      It's two copies. And we are reconsidering this design, due to initialization problems.
      Duplicating state is not that bad, but having constructor side-effects duplicated may be a real disaster. There will be an update on this soon.

  10. Aug 05, 2011


    I also don't like the verbosity of writing

    While this looks still kind of ok, in reality you would probably have something like

    which hides the important part: "field".

    Quick idea to solve it:

    A class can be declared as:

    which declares A and B as "tags". Those tags are no real classes and can be only used for resolving the ambiguity when accessing elements from a super-class (to avoid conflicts with static access for example and prevent people misusing this feature for other things). Now you can write very concisely:

    instead of writing the full class name. I've chosen the @ to mimic the pattern syntax a bit.

    1. Aug 05, 2011

      I don't think that this is a problem at all, but if it were, the syntax to help people out would be close to what you propose:

      class D(v : Int) : @A MyVeryDescriptiveClassName(v), @B AnAlsoVeryDescriptiveClassName(v) 
      // and usage 
      v@B = ...

      This syntax is consistent with labels we use for disambiguation of this.

  11. Aug 09, 2011

    I don't really like the idea of using multiple inheritance. While it's certainly possible to make it work, I'm not sure if it really promotes good design. OTOH using traits like in Scala don't seem to be a good idea either, because it's not always easy to decide when to use inheritance and when to use traits.

    Now it's well known that standard inheritance does two things at once: Creating a subtyping relationship and importing fields/methods from another class. The mix-up of those two concepts is the real reason why multiple inheritance is problematic. If you consider only subtyping for example, nothing bad can happen and there's for example no "diamond problem".

    So what about a more radical approach: Removing "extend" altogether and only allow interface inheritance. To avoid the need for excessive code duplication, there is the possibility to "include" implementation(s) into a class which implements the interface by importing code. This implements the "importing behavior" of inheritance.

    An example (not really fleshed out, just to show the basic idea):

    Some interesting things to note here:

    • We have a clear separation between interface ("what can you do with an object") and implementation ("how the object does it")
    • Variables are always declared with interfaces, objects are always created from classes. So both can live in separate namespaces.
    • There is no "first class citizen" as with inheritance anymore: All interfaces and all implementations are "equal". So the developer don't need to decide, what to use and why.
    • You create classes more like using a construction kit of implementations. No more big classes, just "snippets" of implementations
    • No deep class hierachies anymore: Just a single level
    • While class Array/MutableArray get for example the implementation of resize, but since its not exposed in the interface, it's not available for use (and may be removed by the compiler)
    1. Sep 02, 2011

      This solution is basically a restricted version of mixins (restricted because classes cannot define their own members) and has three basic concepts instead of two. Besides, initialization logic (i.e. constructors) will be problematic in this setting.

      Please, refer to my blog posts intended to discuss multiple inheritance: Part 1 and Part 2.

  12. Aug 12, 2011

    Groovy also has @Delegate annotation

  13. Sep 16, 2011

    Could we have a 'this' return type to simplify method chaining?

    In Java I sometimes face a problem with method chaining and inheritance:

    Also it is not clear from signature, whether method modifies existing object or creates and returns new one. /* AFAIK, Qt uses both ways in their QString... */

    A 'this' return type is just a syntax sugar and should be compiled in simple consequent calls.

    1. Sep 16, 2011

      Yes, we even have it in the current grammar (though it is not supported by the type checker yet).

      You'd just say

      open class Base() { 
        fun foo() : This { 
          return this; 
      class Derived() : Base() { 
        fun bar() : This = this 
      val derived : Derived = Derived().foo().bar()
      1. Oct 19, 2011

        Ugh.  Having "This" and "this" vary only by case is annoying.  No modern Algol-family language should use uppercase keywords!

        1. Oct 19, 2011

          Think of This as an identifier if it bothers you as a keyword
          + This is a type, and this is an expression. Seems to be hard to confuse the two as they arrear in different contexts.

  14. Sep 16, 2011


    I don't think that 'virtual' methods is a good idea. I hate it from the time of Delphi Pascal and then C#. Every time when  I had to subclass a component I almost always found a property or method with a 'virtual' omitted. And as a rule there were no reason for it. I know a lot of libraries for Delphi and C# where the classes where rewritten from scratch just by copying a source code of an existing class. If you publish a class and really want the method to be overridden then mark it explicitly as 'final' or give a programmer a chance to override a 'not virtual' method by something like 'force override' that shows that I know what I do.  When I have to create a subclass then it is my responsibility to override a method or not. It is sad when in a class a single method  without 'virtual' makes inheritance useless.

    1. Sep 16, 2011

      There are many people who won't agree with you. Some of them even say that we should prefer delegation over inheritance.

      1. Sep 20, 2011


        I agree we should. But imagine something like JTable ( or maybe KTable ). With delegation I must rewrite almost every accesstor method. Be sure that a developer (even expert) will forget to make a method virtual. Just learn c# third party visual control libraries foe Win Forms. I don't think that Microsoft made it intentionally. And if you allow to use java as a workaround (awfully) than may be something like 'force override' ?

        1. Sep 20, 2011

          We'll think about it, thanks.

          1. Sep 21, 2011

            I like 'force override' because all defaults tend to be overused.

            About overriding libraries methods it has been said above that

            Best practices say that you should not allow these hacks anyway.

            But best practices usually dont sound so much dictatorial. The best practice probably was

            You should make an effort to avoid these hacks.

            Best practices say that you should make an effort to avoid lying. Yet, lying may be by far the good choice sometime.
            Things are not so black and white.

            These hacks (I call them customizations by the way) may not be the cleanest things on earth, but the alternatives may be worse.
            We are not asking for duck typing.

            Is there any performance considerations with virtual vs non-virtual?

            1. Sep 21, 2011

              Is there any performance considerations with virtual vs non-virtual?

              There were some, with the old inheritance model. With the new model, we still need to review these things.

        2. Sep 20, 2011

          The syntax would be different for Kotlin, but I have wanted this in Java for years:

          Essentially I suggest a constructor syntax with assignment to "this" to have the compiler generate all the glue code for delegation.  This encourages composition over inheritance, and at least for Java, is an elegant use of otherwise illegal syntax.

          I follow up here:

          1. Oct 19, 2011

            I just went over the delegation section.  (Late to the party, I know.)  Thanks!  This is wonderful stuff.


            1. Oct 19, 2011

              Glad to hear this. Sorry I haven't pointed you to our delegation support earlier.

  15. Sep 27, 2011

    If you defined a Trait with all abstract methods, would the compiler generate an vanilla Java interface?


    1. Sep 27, 2011


  16. Oct 05, 2011

    Do you plan syntax for full on ADTs, ala OCaml and friends?

    Nice article on benefits where they use "industrial strength" OCaml -

    I believe your enums would need to support extending for this to work.  Or perhaps extension functions that decorate with new properties.

    I see you are conconsidering your design for class extension.  Would you take this into consideration? 

    1. Oct 05, 2011

      We considering inheritance for enum classes.

  17. Oct 19, 2011

    I may have missed it (this page is so information dense!) but in looking at overriding, is there a way I can do this with simply method assignment?  Something like:

    get() = super<B>.get

    I'd rather not explicitly refer to "v" and consider that part of "B"'s implementation.  The generated code would be identical, I find this mentally cleaner.

    1. Oct 19, 2011

      This is not supported, mainly because you could have a property called get in your base class ('get' is just a 'soft keyword').

      BTW, I wouldn't call this 'method assignment': the rhs of the '=' is the body, i.e. it has the type returned by get, not the type "function that returns what get returns'

  18. Nov 19, 2011


    I wonder why you've removed the new keyword? I kind of like it because it allows to clearly distinguish object creation and a method call.

    1. Nov 19, 2011

      By convention, method names start with lowercase letters and classe names — with uppercase letters. This is a very clear distinction. The new keyword just seems to be syntactic noise.

  19. Dec 02, 2011

    >> This post about multpile inheritance is obsolete <<

    1. Dec 01, 2011

      Thanks for your explanation. The most important thing it says under "Inheritance" is: Note: this design is being reconsidered. See this post.

      We moved from full multiple inheritance to traits, and the problem you are talking about mostly disappeared by itself.

      1. Dec 02, 2011

        Woops... It's very embarrassing, that I've not noticed this important change. But it's good, that we talked about it

        I understand the problem with the multiple inheritance. The solution with stateless traits is very good.

        I've some more questions:

        Can traits contain class objects (constants and static methods)?

        How will secondary constructors look like?

        Are private and protected constructors available?

        Does a class always require a primary constructor like Scala, or is it sufficcient to use only secondary constructors?

        Will Kotlin have events like C#?

        Public Beta
        Can you estimate the release date of the public beta?

        1. Dec 02, 2011

          > Can traits contain class objects (constants and static methods)?

          > How will secondary constructors look like?
          Current syntax is as follows:

          > Are private and protected constructors available?
          Yes. The syntax for visibility modifiers for primary constructors is a little weird:

          This is borrowed from Scala, and we couldn't come up with anything better. Our hope is that those reduced-visibility constructors are not that much needed in Kotlin, after all. Singletons, for example, are naturally done with object declarations, classes with only static members are not present, etc.

          > Does a class always require a primary constructor like Scala, or is it sufficient to use only secondary constructors?
          Currently, a class is required to have a primary constructor.

          > Will Kotlin have events like C#?
          Yes, it does. You can write a class that supports += for adding items and has an invoke(...) function to call all the added functions.

          > Can you estimate the release date of the public beta?
          We have started an internal preview this week. As soon as it is ready, it goes public. And I hope it will be soon.

            1. Dec 18, 2013

              Yes, secondary constructors have been removed. They will be put back one day, but not very soon

  20. Jan 09, 2012

    Please, consider a more short variant for keywords "virtual" and "override", for example "open", "redef". I do not see any good reason to explicit use of "abstract" modifier: any method without a body declaration automatically becomes abstract.

    1. Jan 09, 2012

      We have replaced virtual with open already. Thanks for reminding, I'll update the docs.

      Your proposal about "abstract" is appealing, we'll think about it. Thanks again

      1. Jan 09, 2012

        Implied abstract is nicely logical and minimal.  On the other hand having the word "abstract" helps me scan documentation or code and grok meaning explicitly, that is, keep a smaller mental parser running when browsing code.  Humans like redundancy and I read code far more than I compile it.  (Please don't take my point to absurd lengths, however. :) )

  21. Feb 16, 2012

    Is there any plan to add something like Ceylon's enumerated classes?  Where an open class declares all of its subtypes and no other subtypes can be created.

    This would be useful when pattern matching on type.  If there was a clause in the when expression for all subtypes the else clause could be omitted.  When a new subtype was added the compiler would force you to add a clause for the new subtype wherever you pattern match on type.  This is already possible with enum classes but it would be good if it were possible with ordinary classes.

    This would make pattern matching a type-safe replacement for the visitor pattern which is useful but clunky and not very readable.

    Scala achieves the same thing with sealed classes but I don't like the restriction of having to define all your subtypes in the same file.

    1. Feb 16, 2012

      Please, see Enum classes

      1. Feb 17, 2012

        I know it works for enum classes, I was wondering if it could be extended to regular classes. If you have a big hierarchy or big classes it's not an option to define then all in the same enum class.

        The codebase I work on has a large hierarchy of large domain classes. There's no way they could be defined as members of an enum class. But it would be very useful if the compiler forced you to cover all cases when pattern matching on type.

        1. Feb 17, 2012

          If you have a big hierarchy or big classes it's not an option to define then all in the same enum class.

          That's right. Scala's and Ceylon's approaches seem to be infeasible/inconvenient in this case either:

          • Scala's sealed classes have to sit in the same file
          • Ceylon's enumerated classes must be all listed, which is not impossible but ugly when you have a hundred of them

          What we could in principle do in Kotlin is allow a "sealed" class to have subclasses only within the same module...

          1. Feb 17, 2012

            That would be excellent.  And I agree, that's a nicer way of doing it than Scala's and Ceylon's.

  22. Feb 17, 2012

    Delegation section, example code:

    must be

    or var instead val.

    1. Feb 18, 2012

      Fixed, thanks!

      1. Feb 18, 2012

        Not all, main constructor does not declare property.
        Add val or var, as in my comment.

        1. Feb 19, 2012

          Thanks again.

  23. Jun 07, 2012

    I think I met a problem. So, if I have a Java class like this:

    it seems not same as in Kotlin:

    Then what's a solution, in Android it's a problem.

    1. Jun 07, 2012

      Currently, the only way to create something static in Kotlin is to declare it on the package level.
      We are thinking about a "const" annotation that would turn a val into a Java's static constant

      1. Jun 07, 2012

        Yes it might make sense, but why not just like in class object scope? I mean if just inside class A scope then it's regular field, but if inside class object, then it is also static as in Java?

        1. Jun 07, 2012

          This might work. We'll think about it. Thanks.

          I created an issue here:

          1. Jun 07, 2012

            Okay, thank you for always very fast responses.

  24. Jun 27, 2012

    Don't you think that forcing to use open keyword to be overridable is just too aggressive? Most of your clients will come from Java and this moment is going to be painful, I think....

    May be it's better to keep Java approach and write "final" keyword each time you want to prevent overriding instead of using "open" to enable.

    1. Jul 02, 2012

      Yes, this may be reconsidered. See comments above.

    2. Jul 02, 2012

      I think it is very bad idea to keep Java approach in this. Normally you don't want to extend class, that was not designed to be exteded from, except for placing some hacking logic and avoid refactoring, which is bad.

      Such restrictive rules force you to design your extendable class and make it to have special methods to be overriden in inheritors. If someone wants to extend final class he will have to redesign it to support inheritance. This approach works very well in C#.

      1. Jul 02, 2012

        I agree, I can't see any reasons to make classes open by default except 1) because that's what Java devs are used to and 2) because it allows hacking of other people's code. Are there any others?

        I think this is a good feature. Anything that discourages the over-use of inheritance is a good thing IMHO.

      2. Apr 14, 2013

        I agree too. One of the main reasons to have a new language is to fix the issues and correct the mistakes in current languages. I believe having all methods extendable by default, in java classes was a mistake and it needs to be fixed here.

  25. Jul 09, 2012

    Anonymous initializers for members(as in Your Example) are no longer supported?

    1. Jul 09, 2012

      There was never such a thing as "anonymous initializers for members". The "{...}" in the class body is just an anonymous initializer (exactly like in Java). The current syntax demand a semicolon, I've corrected the example above.

  26. Jul 09, 2012

    You have written that:

    If a class does not have any constructors declared, one cannot instantiate it:

    but it's compiled.

    1. Jul 09, 2012

      This paragraph was outdated. Fixed, thanks

  27. Jul 09, 2012

    I think in this document miss information about the syntax for visibility modifiers for constructor

    1. Jul 09, 2012

      Good point. Mind to file an issue in the tracker? Thanks

  28. Jul 21, 2012

    There is no support for secondary constructors, as it looks in

    But currently a lot of Java frameworks rely on having default constructor, actually many frameworks, which do some sort of cglib proxy work: Hibernate, Spring, Guice, ... For example, Spring: while it's good to use constructor injection, to be able to create AOP proxy on class-level CGLIB requires class to also have default constructor to instantiate proxies.

    Same thing with hibernate: it is required to have default constructor for thing to work, but it also usefull to have some constructors with data to work in tests/user code.

    What are plans to support this kind of frameworks?

    While such kind of technique could be considered "evil", it is quite wide spread. It could be thought as there are two ways of constructing class (Hibernate): one "legal" for programmer, and one "internal" for library to create some kind of reflection magic. So one possible "hack" solution is a kind of feature which enables this backdoor in compiled bytecode, but doesn't allow userland code to use it.

    Some other very concrete library-related considerations (don't know if it is important for language design..): it seems like "final" by default on class and methods would be a pain point with cglib also as far as final on class is validated, but final on method just silently ignored and just don't intercept call.

    Hope this things could be solved this or other better way.

    1. Jul 23, 2012

      Factory methods cover everything you need, if you already have a default constructor.

  29. Sep 04, 2012

    Have you considered adding something like C#'s object initializers? It seems like the most natural way to set one or more properties when you create an object, without messing with the constructor:

    I'm not positive, but it doesn't seem like this would interfere with your existing syntax, and is much cleaner than

    1. Sep 04, 2012

      You can use named arguments to mimic this in Kotlin:

      class MyClass(val a: Int, val b: String) 
      fun test() { 
          a = 1, 
          b = "hello" 

      For more sophisticated cases builders will work nicely.

      1. Sep 04, 2012

        I agree that named constructor arguments offer an alternative, but it seems like there are a few downsides:

        1. You have to declare all of your initializable properties in the constructor. This seems inelegant if you have a lot of them, or if you want to add proper comments to them.
        2. It seems like Kotlin constructors with arguments, even if they all have defaults, don't play well with some Java libraries. I was just using one yesterday (Morphia, for mongodb integration) that did not accept my default argument constructor as a valid default constructor. 

        The web demo for the builders is interesting. As of M2, this functionality was still broken in the compiler. Does the web demo know something I don't?

        As always, thanks for the timely and thoughtful reply, Andrey. 

        1. Sep 04, 2012

          1 & 2: It is a little wordy, but you can declare a factory method that would suite all your needs:

          class MyClass { 
            var a: Int = 0 
            var b: String = "" 
          fun MyClass(a: Int, b: String): MyClass { 
            val r = MyClass() 
            r.a = a 
            r.b = b 
            return r 
          fun test() { 
              a = 1, 
              b = "hello" 

          About builders: the webdemo code compiles fine, the one in the wiki examples does not, for it uses an unsupported feature.

          1. Sep 04, 2012

            Yes, very wordy and certainly not DRY.

        2. Sep 04, 2012

          Perhaps your need something like this?

          1. Sep 04, 2012

            Secondary constructors are no longer supported.(KT-2363)
            But you can write:


            and use:

            1. Sep 05, 2012

              Thanks. I didn't think there was a way to do secondary constructors. 

              The first solution (having a function that wraps the constructor) has the usage syntax I'm looking for. It would be nice if it were built in, though, in order to not have to make that function for every class I'd like to use it on. Is there a way it can be genericized, like the second solution, to apply to any class?

              1. Sep 05, 2012

                Maybe next solution will suit you:

              2. Sep 05, 2012


                but the following code does not compile:

                I think it's bug (submited KT-2728)

                1. Sep 05, 2012

                  Nice example! And thanks for the report.

                2. Sep 05, 2012

                  Cool, looks like a good solution. Hopefully it can get addressed by M3 :)

  30. Sep 09, 2012

    Is it possible to make a proxy for trait, like in Java Proxy.newProxyInstance ?

    1. Sep 10, 2012

      Yes, you can use the same Java API: Proxy.newProxyInstance

  31. Sep 13, 2012

    I studying the possibility of using Kotlin in a real world application, based on JavaFX.

    While I am still testing I have created a library, that I will publish in github, with that you can use a DSL for building JavaFX ala ScalaFX, but without the need to create wrappers, just with extension methods.

    Something like this:

    I still don't like the kotlin constructor body way and the lacks of some instance initialization led me to create the "with" extension.

    And I need one thing by now, a way to get a class for an interface, there is one way? Because the FrameworkFactory().javaClass way only works for classes apparently.

    ERROR: C:\Projetos\GitHub\KotLife\kcore\klife.application\src\main\kotlin\life\application\OSGIManager.kt: (22, 19) Expression 'FrameworkFactory' of type 'org.jetbrains.jet.lang.types.NamespaceType@1278b730' cannot be invoked as a function

    And just one opinion, this way to get the class is not clear. It gives the impression that you are creating an instance of FrameworkFactory and getting the class after (and maybe that is what is really happening which explains the previous error).

    1. Sep 13, 2012

      Use javaClass<FrameworkFactory>()

      1. Sep 14, 2012

        Thank you very much!

  32. Sep 18, 2012

    1. Sep 18, 2012

      Надо полагать, один конструктор родительского класса выражается через другой.

      1. Sep 18, 2012

        Да, но есть ньюанс.... если я создаю данный класс из кода, то мне надо отправить ТОЛЬКО объект контекста. А если я этот же класс пропишу в манифесте, то система его вызовет через конструктор с атрибутами. А очень часто требуется объявлять один и тот же класс и так и так. Возможен ли вариант синтаксиса, что то типа:

        class A(), (context : Context)(context : Context, attrs : AttributeSet) : B(),(context),(context,attrs){



        Иначе придется реализовывать класс от конструктора с максимальным кол-вом параметров,от него наследовать другой, что бы реализовать конструктор с меньшим кол-вом параметров и т.д. :

        class A(context : Context, attrs : AttributeSet, flag: Boolean) : B (context, attrs, flag) { }

        class C(context : Context) : A(context, null, false) { }

        получается что то типа этого. И каждый из них использовать в нужном месте. А этого бы не хотелось делать, только для того что бы переопределить один конструктор. 

        как сейчас многие говорят - пичалька

        1. Sep 18, 2012

          Можно написать как то так:

          или так:

          Единственное, возможно будет небольшой оверхед, т.к. мы всегда будем вызывать более сложный(судя по сорцам) конструктор.

          1. Sep 18, 2012

            Огромное спасибо, это действительно может решить проблему.....

  33. Nov 16, 2012

    Will properties be supported in traits? (I tried in the editor and it gives me an error)

    1. Nov 16, 2012

      Properties are supported in traits. State is not supported, though, so your properties must be either abstract or provide custom getters and setters

  34. Dec 11, 2012

    How are package-level functions accessed from Java code?
    As I understand, pseudo-class "namespace" is created and methods are called from it. But in my IDEA it saw only methods from one file, when methods were declared in 2 files.

    How does this mechanism of creating "namespace" class work? 

    1. Dec 11, 2012

      The "namespace" class must contain functions from all the files in the same package. If it didn't contain all of them, it is a bug.

  35. Dec 14, 2012

    On open vs closed: I'm quite sure that functions in C++ are non-virtual by default because of performance, and not to propagate designing for inheritance. I guess things are different on the JVM, but as I don't know how the JIT compiler handles this: Do open functions have a drawback in terms of speed as well?
    To help solving the possible problems with overriding, I have a suggestion that isn't as limiting as final: In many cases, overriding does not cause trouble when the child class keeps calling the implementation of its parent - this is common behavior for constructors, but I don't know any language that offers a way to enforce this for arbitrary methods (maybe because it's hard to find a good keyword for such a concept ;-).
    Take setters as an example: I can't think of any reason why a subclass shouldn't have the option to be notified when an inherited property is changed - but with a final setter, you have to declare and call hooks, which means

    • much more typing (at least for simple setters)
    • cluttered method list (a pair of "willChange…" and "didChange…" methods for each property)

    With a notation to enforce calling super's implementation, this burden would vanish - as would the need to find proper names for the hooks.
    [as that is my first post here: Good work - I really hope Kotlin keeps evolving in the direction you have taken so far]

    1. Dec 17, 2012

      Thanks for the feedback. We'll take you use case into account.

  36. Dec 30, 2012

    Kotlin can declare classes with static class objects inside or directly object types... but both are defined as instances in the parent ("MyClass.$instance.something...")

    I still think that, in some cases, mostly when interoping with Java, access a type like this is ugly! But I undestand the points of maintaining this feature. So, I am proposing a way to declare static types, just like static classes in C#.

    Kotlin could allow something like this (by annotation or by keywords)

    and that then could be translated as the following

    I think that is an easy feature to implement and good to maintain the compatibility with old Java code.

    1. Jan 09, 2013

      Why not simply declare a bunch of top-level members in a package?

  37. Jan 18, 2013

    Is it possible to pass class references as function arguments?

    Example 1:

    // read value of specified type: 
    val counter = read(Int);

    I tried to implement it this way:

    fun read<T>(valueType: Class<T>):T { 
        var line = readLine(); 
        if (valueType == Int) { 
            return line.toInt() as T; 
        } else { 
            // ... do something else 

    Alas, compiler doesn't like neither valueType == Int (because he treats Int as class object), nor valueType == Class<Int> (function invocation expected).
    I tried another way to call function:

    val counter = read<Int>();

    But still i can't find how to compare types.
    Is it possible or not?

    1. Jan 18, 2013

      Another example: function that reads array from standard input:

      fun readArray<T>():Array<T> { 
         var line:String = readLine(); 
         var array = ArrayList<T>(); 
         when (T) { 
             // ??????? what to write here? 
         return array; 
    2. Jan 18, 2013

      Use javaClass<Int>(), it gives you a normal Java reflection object (java.lang.Class)

  38. Apr 18, 2013

    probably a late suggestion, but the current way of accessing properties makes me think that it's a public field and i'm accessing it directly.

    instead, we could use following syntax:

    1. Apr 18, 2013

      The property is public (the field isn't), and the experience of C# community shows that this is a good thing.

  39. Apr 22, 2013

    This is cool. You can hide the actual implementation (BaseImpl) from clients.

  40. Apr 22, 2013

    Apparently the secondary constructors have been dropped. 

    Any plan to add them back?

    1. Apr 22, 2013

      No. They are not needed.

  41. Jul 18, 2013

    few points and questions

    1. As my understanding, functions in "Trait",by default, are open. 

    2. "final" functions are not allowed in trait. Am I right? 

    3. overriding individual "getter" and "setter", causing compile error in my pc.

    4 - "abstract" is missing for "create" function.

    5 - Parentheses, for Factory, are missing in following code.   

    1. Jul 19, 2013

      1. Fixed, thanks
      2. No. Final members are allowed in traits

      3. We dropped the ability to override individual accessors
      4. Fixed, thanks
      5. Fixed, thanks

  42. Oct 07, 2013

    Couple of dumb questions.

    1. Why do you need both override and open keywords for overriding methods. Is it difficult task for compiler to resolve the following foo() method as virtual and allow overriding in derived class?

    2. The following one is a valid code in Kotlin. It compiles without any problems, but I do not understand why output is Base not Extended?

    3. Well, the other point is that you call override and open annotations but when I try the following example it fails. What is the problem with the code? Or these keywords are not really annotations?

    1. Oct 07, 2013

      1. I'm not sure I understand the question. If you are asking why 'open' is required, then it's a design decision in the language ("No accidental overridability"), not a technical necessity. This decision may be reconsidered.

      Regarding your example: the two classes can sit in different modules, thus the compiler might not know anything about Derived while compiling Base.

      2. Because extension functions are not members, they do not override members (but may overload them), and members always win over extensions if both are applicable.

      3. This is a temporary limitation of the current implementation. Our parser treats "open" and "override" as soft keywords rather than annotations for now. This means that you can use "open" as an identifier (e.g. a variable name), but when encountered in front of a declaration it is treated as a modifier. We will turn all modifiers into annotations when annotation support is completed in the compiler.

      1. Oct 07, 2013

        >> If you are asking why 'open' is required, then it's a design decision in the language ("No accidental overridability"), not a technical necessity.

        That is the answer to my question, thnx.

  43. Oct 17, 2013

    About Properties

    I love the way Kotlin does operator overloading, by convention; however, property access (like "bean.prop") appears to be restricted to field properties.  It would be great if getter/setters would be mapped to properties such that I can switch implementation between field properties and methods.   

    For example:

    Also this documentation is missing the great milestone 5.3 info on property delegates.  

    1. Oct 17, 2013

      There's no need in making a get-functions look like a property in Kotlin. If you need a property, use a property:

      class Person(val first: String, val last: String) { 
        val fullName: String 
          get() = "${first} ${last}" 

      This would be desirable for Java classes, but there are problems with inheritance.

      1. Nov 06, 2013

        I can see how this works for Kotlin only projects, but we still have a lot of Java code (most objects in Java).  It would be great if Kotlin used convention for property access, allowing the Java "properties" to stand evenly with Kotlin properties in Kotlin files (I know Java does not have real properties).  Accessing fields on Java objects from Kotlin could be done with "$field".  

        Loving Kotlin, Thank you

        1. Nov 07, 2013

          Yes, it would be great indeed. Unfortunately, inheritance presents substantial challenges in this regard, which we don't yet have a solution for.

  44. Dec 18, 2013

    How can i access delegated method when overriding it?

    For example: 

    says to me that i am trying to run abstract function MutableCollection.add and gives an error, but i want to run ArrayList.add insted.

    1. Dec 18, 2013

      This is a bug, please report to the tracker.

      1. Dec 19, 2013

        I think this is not a bug, but a concept lack. I man

        is equivalent to

        so T is supertype, not A.
        And "by A()" is not about inheritence, but about implementation.
        And also:

        so accessing A via super is inappropriate.
        The solution is to give me an option do declare delegate as val or var

        1. Dec 19, 2013

          I see what you mean, but complicating the syntax so much for this cause seems to be an overkill.

  45. Jan 10, 2014

    there is some fancy error with property override^

    gives NPE in line marked with /**/ . Indeed i can't figure how it have to work theorticely, but.
    1. Can I override value with stronger type? Yes i can.
    2. Can I pass to constructor stronger type then it expects? yes i can. Will it brake construction logic? No, because subtype alvays supports parent's interface.
    3. But in combination... it fails.

    And if i don't know the implementation of parent class?

    1. Jan 10, 2014

      This is a well-known problem in OO-languages: C++, C#, Java, Scala, all have it, and Kotlin does not solve it either: calling a virtual function (in this case — a property getter) in constructor of an open class. We should probably issue a warning here. A workaround would be to say $aa.x = 3 instead of aa.x = 3

      1. Jan 10, 2014

        First of all, there should be specific error message, not NPE. At least. Then. As i see there now there are only three posible cases situations:

        1. Virtual function that is never called in construction: fine;
        2. Function called in constructor is final. Perfect;
        3. virtual function is called in constructor: big problems. Always.

        So if that guy wrote some class, gave me an open function and called this function in constructor the function is closed for me.
        So calling virtuals inside constructor should be not only warned, but strongly permited as a source of guaranteed errors. It have to force developer to use safe workaround.

  46. Jun 25, 2014

    How do the action scope of a class work in Kotlin?

    I define a class:

    package cn.bee.utils

    object XX {
    public fun calc() = 10

    Should XX be not visible for classes in the other package?
    However, I can call it in the other package:

    For example:


    Why do it can work?

    1. Jun 25, 2014

      Default visibility in Kotlin is internal which means "visible inside a module", so XX should be visible to other packages in the same module.
      To make a top-level declaration private to a package, just mark it private

  47. Jun 28, 2014

    What does the `class object` construct offer? Maybe it's conceptually a little cleaner, but does it justify breaking compatibility with Java (both conceptually and literally)?

    The biggest problem with static methods I've found is their incompatibility with Dependency Injection and mocking. I don't believe this fixes it, because you're still coding to a type name. I admit, passing the type as if it were an object is kind of cool. Yet I wonder if that couldn't be accomplished differently, with a function that wraps a type containing static methods into an object.

    Btw, something that I hope from every new language is explicit support for modern design patterns like dependency injection, unit testing/mocking, property change notification (and even binding), etc. Why do you think new languages don't take this direction?

  48. Jul 06, 2014

    In a method (or a var/val), is it possible to require 2+ traits for a parameter in a kotlin/elegant way ?
    fun stuff(builder:Appendable & CharSequence) or fun stuff(builder:Appendable + CharSequence)

    At the moment, it can be done this way (but it's really dirty and it must break things somewhere in the ide ?)

    In another koltin module

    In another kotlin-android module

    1. Jul 06, 2014

      Try something like:

    2. Jul 06, 2014

      When you don't know how write something in Kotlin, but know how write it in Java – try to write it in Java and convert to Kotlin.

      Anyway feel free to ask any questions here or in our forum(

      1. Jul 06, 2014

        Thanks and thanks for the 2 valuable tips.