Skip to content

Instantly share code, notes, and snippets.

@dodalovic
Last active October 29, 2020 00:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dodalovic/c29dd2a0976bef12407d4edc97243c68 to your computer and use it in GitHub Desktop.
Save dodalovic/c29dd2a0976bef12407d4edc97243c68 to your computer and use it in GitHub Desktop.
Overloaded constructors in Kotlin
class Hotel {
val name: String
val city: String
val stars: Int
private var jimIncluded = false
constructor(name: String, city: String, stars: Int) {
this.name = name
this.city = city
this.stars = stars
}
constructor(name: String, city: String, stars: Int, jimIncluded: Boolean) : this(name, city, stars) {
this.jimIncluded = jimIncluded
}
override fun toString(): String {
return """[ name : $name, city : $city, stars : $stars, jimIncluded : $jimIncluded ]"""
}
}
val cheapHotel = Hotel("Fake Hilton", "Crappytown", 2)
val fiveStarHotel = Hotel("Hilton", "NYC", 5, true)
println(cheapHotel)
println(fiveStarHotel)
[ name : Fake Hilton, city : Crappytown, stars : 2, jimIncluded : false ]
[ name : Hilton, city : NYC, stars : 5, jimIncluded : true ]
class Hotel(val name: String, val city: String, val stars: Int) {
private var jimIncluded = false
constructor(name: String, city: String, stars: Int, jimIncluded: Boolean) : this(name, city, stars) {
this.jimIncluded = jimIncluded
}
override fun toString(): String {
return """[ name : $name, city : $city, stars : $stars, jimIncluded : $jimIncluded ]"""
}
}
val cheapHotel = Hotel("Fake Hilton", "Crappytown", 2)
val fiveStarHotel = Hotel("Hilton", "NYC", 5, true)
println(cheapHotel)
println(fiveStarHotel)
[ name : Fake Hilton, city : Crappytown, stars : 2, jimIncluded : false ]
[ name : Hilton, city : NYC, stars : 5, jimIncluded : true ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment