Search code examples
kotlinandroid-studioclassenumsproperties

Does it matter if I omit the 'val' keyword when adding a parameter/property to an enum class, doesn't seem to make any difference to the enum entries


When creating an enum class I am unsure what the difference is between adding adding val to a parameter and not. When providing arguments for said parameter for each enum entry there seems to be no difference. Hopefully someone can explain.

This is without 'val'

image_1

This is with 'val

image_2

Thanks.

I have tried looking everywhere, the only difference it seems is that one is a parameter and one is a property but i dont really understand the difference. I am still fairly new to kotlin/android studio.


Solution

  • if you don't add val you can't access it later, it won't be a property of the class, it would be just an argument that you have passed to the constructor and it would be pointless in an enum

    enum class ScreenSize(width: Int, height: Int) { // not declared as val
        Big(1000, 1600),
        Medium(700, 1000),
        Small(500, 700)
    }
    
    fun drawScreen(screenSize: ScreenSize) {
        //Compile error
        drawRect(
            width = screenSize.width,
            height = screenSize.height,
        )
    }
    
    fun drawRect(width: Int, height: Int) {
        .....
    }