Constructors in Kotlin


#1

I was wondering about the syntax for constructors in Kotlin. How do deal with them in an optically pleasing way?

data class Person(val firstName: String,
                  var lastName: String,
                  val age: Int) {

data class Person(
                  val firstName: String,
                  var lastName: String,
                  val age: Int
           ) {


data class Person(val firstName: String, var lastName: String, val age: Int) {

data class Person(val firstName: String,
                  var lastName: String,
                  val age: Int)
{


I’m not really feeling comfortable with wrapping the properties in () followed by { because it just doesn’t read nicely, especially for longer lists. It’s getting even messier when you start adding modifiers to those properties. Can you specify getters/setters for properties initialized in the constructor?

How is everybody else dealing with this?


#2

See example of how we usually deal with this in Kotlin codebase: https://github.com/JetBrains/kotlin/blob/master/core/serialization/src/org/jetbrains/kotlin/serialization/deserialization/context.kt


#3

Thanks for sharing!

How do you deal with delegated properties? How do you provide custom getters/setters for properties that are initialized in a constructor?


#4

Not sure if I get your question right, but delegated properties and properties with custom accessors cannot appear in the constructor.


#5

That sounds like a rather peculiar limitation. Basically I can only do something like that then?

 
data class Constr(private var _y: String) {
    public var y: String by Delegates.observable(_y, {(propertyMetadata, old, new) -> println("$old -> $new")})
}

#6

In this case you need not a backing property for _y, just a constructor parameter (omit "private var"). And if you're constructing an observable property with an initial value, then yes, this is the best you can get, because you still need separate declarations for the initial value and for the property itself.


#7

Thanks for the clarification.