What is the difference between constructor parameters and member variables in Kotlin classes?

216 Views Asked by At

I discovered that both constructor parameters and member variables behave almost the same way.

The only difference is that: the noOfSides cannot be changed inside class Square, whereas noOfSideVar can be changed inside the class Square

Code that I have written:

fun main(args: Array<String>) {
    var square1 = Square(4)
    println("Parameter form: ${square1.noOfSides}")
    println("Variable form: ${square1.noOfSideVar}")

    square1.noOfSides = 10
    square1.noOfSideVar = 50

    println("New Parameter form: ${square1.noOfSides}")
    println("New Variable form: ${square1.noOfSideVar}")

}

open class Polygon(var noOfSides: Int)

class Square(noOfSides: Int) : Polygon(noOfSides) {

    var noOfSideVar = 7
    fun area(): Int {
        return noOfSides * noOfSides
    }

}

The output of the above code:

Parameter form: 4
Variable form: 7
New Parameter form: 10
New Variable form: 50

Process finished with exit code 0

If I am having any sort of misconception, please clear it. I know this is a fundamental question but I am quite confused as a beginner.

0

There are 0 best solutions below