xxxxxxxxxx
Although secondary constructors are not that common in Kotlin. The most common use of secondary constructor comes up when you need to extend a class that provides multiple constructors that initialize the class in different ways.
xxxxxxxxxx
class SmartDevice(val name: String, val category: String) {//Primary constructor. Can be instantiated without parameters.
var deviceStatus = "online"
//Secondary constructor "of type primary constructor (this)"
//Required to provide primary constructor parameters if applicable.
constructor(name: String, category: String, statusCode: Int) : this(name, category) {
deviceStatus = when (statusCode) {
0 -> "offline"
1 -> "online"
else -> "unknown"
}
}
}
xxxxxxxxxx
class Log {
constructor(data: String) {
// some code
}
constructor(data: String, numberOfData: Int) {
// some code
}
}