Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Last active February 2, 2020 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magdamiu/31c4df7e3bfb5c18c6741a6a3af85a51 to your computer and use it in GitHub Desktop.
Save magdamiu/31c4df7e3bfb5c18c6741a6a3af85a51 to your computer and use it in GitHub Desktop.
Constructors and init block in Kotlin
// primary constructor with fullName property (setter & getter)
class Person(val fullName: String) { /*...*/ }
// define a secondary constructor
class Person(val fullName: String) {
val age: Int
get() {
return 18
}
// secondary constructor
constructor(fullName: String, age: Int) : this(fullName) {}
}
// instance of the class
val john = Person("John", 24)
// init block
class Person(val fullName: String) {
var isLongName = false
init {
isLongName = fullName.length > 15
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment