Reputation: 664
I have an expression when
in my code, which does:
when{
currentOpperand.text.toString().endsWith("+") ||
currentOpperand.text.toString().endsWith("-") ||
currentOpperand.text.toString().endsWith("÷") ||
currentOpperand.text.toString().endsWith("×") ||
currentOpperand.text.toString().endsWith(".") ||
currentOpperand.text.toString().endsWith("")
->{
currentOpperand.text = currentOpperand.text.toString() + ""
}
I want to make this code shorter, like:
when{
currentOpperand.text.toString().endsWith("+", "-", "÷", "×", ".", "") ->{
currentOpperand.text = currentOpperand.text.toString() + ""
}
But android studio gives me an error:
None of the following functions can be called with the argument supplied
If it's possible, comment please another way to do these using things like: lastIndexOfAny
or etc. (I want to do this action in any way possible with the shortest result in code)
Upvotes: 3
Views: 1043
Reputation: 9892
You can use the extension function. Here is how it looks:
fun String.endsWithMulti(vararg chars: Char): Boolean
{
chars.forEach {
if (endsWith(it))
{
return true
}
}
return false
}
fun main()
{
// Test
println("TEST_+".endsWithMulti('+', '-', '/', '*')) // true
println("TEST_-".endsWithMulti('+', '-', '/', '*')) // true
println("TEST_O".endsWithMulti('+', '-', '/', '*')) // false
}
So your when
statement will look something like this:
when
{
stringYouWantToCheck.endsWithMulti('+', '-', '÷', '×', '.') ->
{
// do something
}
else ->
{
// string doesn't end with '+', '-', '÷', '×', '.'
}
}
As @IR42 mentioned in the comment You can simplify endsWithMulti
fun String.endsWithMulti(vararg chars: Char): Boolean
{
return chars.any {
endsWith(it)
}
}
Upvotes: 2
Reputation: 13609
You could use regex:
val regex = """\+|\.|\-|×|÷| $""".toRegex()
val matched = regex.containsMatchIn(currentOpperand.text.toString())
if(matched)
currentOpperand.text = currentOpperand.text.toString() + "" //this line is Questionable,maybe you should do other things.
Upvotes: 0
Reputation: 6186
You can do like this:
var doesExist = currentOpperand.text.last().toString() in arrayOf("+", "-", "÷", "×", ".", "")
when{
doesExist ->{
currentOpperand.text = currentOpperand.text.toString() + ""
}
}
But the question is: currentOpperand.text = currentOpperand.text.toString() + ""
is redundant, of no use. Why you're doing so?
Upvotes: 1