Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@mhshams /Example.kt secret
Last active

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
open class Person(val firstName: String, val lastName: String, val age: Int)
class Employee(firstName: String, lastName: String, age: Int, val position: String)
: Person(firstName, lastName, age)

Class definition and object initialisation are different concerns. Mixing them together, in kotlin, makes the code unclear and hard to follow/understand.

In some occasional cases, like flat data classes (e.g. Person in above example), it makes the code shorter and fancier. But when it comes to complex classes with inheritance and ..., I would prefer separate constructors (like Java constructors).


Looks like a few newlines could improve the situation a lot


@abreslav Usually, when I'm looking at a class, the first things I want to know is the class name and it's parents. properties and initialization come later.

As I said, kotlin (and scala) style sometimes is short and nice, but, I believe, it shouldn't be the only option.


IMO, the best constructors are in Dart -- they look just like in Java, except that there is a syntax sugar for automatically assigning constructor parameters to corresponding fields. Looks like this:

class Person {
  String firstName;
  String lastName;
  int age;

  Person(this.firstName, this.lastName, this.age);

Even though Dart is a dynamically typed language and static type annotations are only optional, the spec mandates that the static type of a constructor argument is the same as the type of the corresponding field, so there's no type loss here.

In pseudo-Kotlin, it could look like this:

class Person {
  val firstName: String
  val lastName: String
  val age: Int

  Person(this.firstName, this.lastName, this.age);
  //new(this.firstName, this.lastName, this.age);

Not bad. The commented line is a variant that uses new instead of the class name.

(I wanted to suggest adopting named constructors from Dart too, but that wouldn't work in Kotlin because 1. it would be ambiguous (named ctor vs. method call on companion object), 2. it would violate the unwritten policy of "single constructor ought to be enough for anybody", so no luck here.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.