dev_swat
dev_swat

Reputation: 1344

what is default value type of kotlin class constructor parameter?

class Greeter(name: String) {

    fun greet() {
       println("Hello, $name")
    }
}

fun main(args: Array<String>) {
    Greeter(args[0]).greet()
}

for above program I got this error

Unresolved reference: name

but when I add var or val

class Greeter(var name: String) {

or

class Greeter(val name: String) {

then program works fine, so why I need to add var or val to name, what is default type for constructor parameter val or var and why program gives me error when I not mention var or val

Upvotes: 3

Views: 1176

Answers (3)

Mark Kumar
Mark Kumar

Reputation: 21

Adding val or var makes the parameter a property and can be accessed in the whole class. Without this, it is only accessible inside init{}

Upvotes: 1

Harshvardhan Joshi
Harshvardhan Joshi

Reputation: 3193

The question is not making any sense, But the problem you are facing does make sense. In your case, the approach you are using is,

Wrong-Way:

// here name is just a dependency/value which will be used by the Greeter
// but since it is not assigned to any class members,
// it will not be accessible for member methods 
class Greeter(name: String) {
  fun greet(){} // can not access the 'name' value
}

Right-Way:

// here name is passed as a parameter but it is also made a class member
// with the same name, this class member will immutable as it is declared as 'val'
class Greeter(val name: String) {
  fun greet(){} // can access the 'name' value
}

You can also replace val with var to make the name a mutable class member.

Upvotes: 0

George Isaac
George Isaac

Reputation: 589

To use your value in the constructor like class Greeter(name: String), you can use init{}

class Greeter(name: String) {
    var string:name = ""
    init{
        this.name = name
    }

   fun greet() {
       println("Hello, $name")
    }
}

or If you use val or var in the constructor it is more like class level variable and can be accessed anywhere inside the class

class Greeter(var name:String){
    fun greet() {
       println("Hello, $name")
    }
}

The variable name can be used directly in the class then. We can also give default values for the variables in both cases.

Upvotes: 1

Related Questions