'How to return a String from a Kotlin method?

I am new to Kotlin. I am simply trying to return a response as a String from a method. But if I use val Str = ""; it is not re-assignable.

Like Java in why can't we re-assign a response to a String which is defined already, and return it.

public fun getCustomers(): String {
  val Str = null;
  val StringRequest = StringRequest(Request.Method.GET, url, Response.Listener<String> { response ->
    Str = response.toString();

  }, Response.ErrorListener {
    it.printStackTrace();
  })

  return Str;
}


Solution 1:[1]

Use var for the Str variable that you have used here because val is like final, and you can't re-assign it.

public fun getCustomers(): String {
  var Str = "";
  val StringRequest = StringRequest(Request.Method.GET, url, Response.Listener<String> { response ->
    Str = response.toString();

  }, Response.ErrorListener {
    it.printStackTrace();
  })

  return Str;
}

Solution 2:[2]

private val customers: String get() {
    var Str = "";
    val StringRequest = StringRequest(Request.Method.GET, url, Response.Listener<String> { response ->
        Str = response.toString();
    }, Response.ErrorListener {
        it.printStackTrace();
    })
    return Str;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aSemy
Solution 2 Dilshod