'I cannot concatenate a variable + string + variable this line of code gives me a error "None of the following functions can called with the argument s
I'm a newcomer in this, and I'm learning kotlin in android studio, and I'm stacked in this error, "None of the following functions can be called with the arguments supplied" when I want to concatenate a variable + string + variable the error appears, and when delete the first variable and the plus signal the error disappears, Could anyone help me whit this? this is the part of the code
/**
* This method is called when the order button is clicked.
*/
fun submitOrder(view: View?) {
var price = quantity * 5
var priceMessage = price + "dollars for " + quantity + " of coffee. Pay up"
displayMessage(priceMessage)
}
Solution 1:[1]
Try String Templates in Kotlin
String templates allow you to include variable references and expressions into strings. When the value of a string is requested, all references and expressions are substituted with actual values.
Take this kotlin example. https://play.kotlinlang.org/byExample/08_productivity_boosters/02_String%20Templates
fun submitOrder(view: View?) {
var price = quantity * 5
*// Templates try like this*
var priceMessage = "$price dollars for $quantity of
coffee. Pay up"
(or)
*//(you can execute command inside like this)*
var priceMessage = "${String.format("%.3f", price)} dollars
for ${quantity+1} of coffee. Pay up"
displayMessage(priceMessage)
}
Solution 2:[2]
price + "dollars for "
won't work because you can't add a string to a number. If you want to concatenate them all, you can do like this using string templates:
val priceMessage = "$price dollars for $quantity of coffee. Pay up"
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 | Pradeepvina |
Solution 2 | Arpit Shukla |