Skip to content

Instantly share code, notes, and snippets.

@renaudcerrato
Last active February 19, 2019 09:11
Show Gist options
  • Save renaudcerrato/393a53fbcee0daec26b63718e7b8067c to your computer and use it in GitHub Desktop.
Save renaudcerrato/393a53fbcee0daec26b63718e7b8067c to your computer and use it in GitHub Desktop.
Kotlin Constructors
// Primary constructor declaration
class Person constructor(name: String) { ... }
// The constructor keyword can be omitted if there's
// no visibility modifiers nor any annotations
class Person(name: String) { ... }
// Property initialization
class Person(_firstName: String, _lastName: String) {
val firstName = _firstName.capitalize()
val lastName = _lastName.capitalize()
val fullName: String
init { // using initializer blocks
fullName = "$firstName $lastName"
}
}
// You can declare properties in the primary constructor
class Person(val firstName: String, val lastName: String, var age: Int)
// Kotlin supports default arguments
class Person(val firstName: String = "John", val lastName: String = "Doe")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment