Skip to content

Instantly share code, notes, and snippets.

@mhshams
Last active August 29, 2015 13:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mhshams/656f464504511d049a36 to your computer and use it in GitHub Desktop.
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)
@mhshams
Copy link
Author

mhshams commented Mar 17, 2014

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).

@abreslav
Copy link

Looks like a few newlines could improve the situation a lot

@mhshams
Copy link
Author

mhshams commented Mar 17, 2014

@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.

@Ladicek
Copy link

Ladicek commented Mar 18, 2014

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 this.xxx 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