Use of constructor parameters


I have a question about the following piece of code, from the Udacity course on Kotlin.
****The code starts here

package Aquarium

class Fish(val friendly: Boolean = true, VolumeNeeded: Int){

    val size: Int
    if (friendly){                                            
        size = VolumeNeeded
        size = VolumeNeeded * 2



fun fishExample(){
      val fish =  Fish(friendly = true, VolumeNeeded = 20)
    println("Is Fish friendly? ${fish.friendly}, how much volume it needs: ${fish.size} cm" )

*****Code ends here

My question is, when the parameter {fish.VolumeNeeded} was passed into the last println statement, it gave an error which was explained as “VolumeNeeded” not being a property of the class. However when {fish.friendly} is passed, it is allowed but it also isnt a property of the class. Why did {VolumeNeeded} produce an error?

Thank you

In the class line, if you add val before VolumeNeeded, it would work. That makes it a property, and since it’s not a property, the value can only be used while the class is being constructed (and not afterward in a function).

Thank you.

I not so sure the udacity course you follow is the best. You say it claims that friendly isn’t a property of Fish which is wrong.
Also you use VolumeNeeded instead of volumeNeeded. This is not necessarialy worng, but the kotlin coding conventions clearly state that all properties and variables should be in cammel case and start with a lower letter. Only classes and interfaces should start with an upper case letter.
This shows that the author either doesn’t know much kotlin or at least never used it outside of personal projects. So if you didn’t pay for the course I consider switching to another course about kotlin. is a great place to start.

I took the same Udacity course (Kotlin Bootcamp for Programmers). The senior instructor was very knowledgeable about Kotlin and its coding conventions.

In my copy of that code, the second ctor parameter is properly spelled as volumeNeeded. And I doubt if it was stated in the course that friendly is not a property.

1 Like