Search code examples
androidkotlinexpressionbigdecimaloperation

Solving error of BigDecimal in Kotlin "Unresolved reference. None of the following candidates is applicable because of receiver type mismatch"


I am doing this in Android Kotlin

val simpleInterest = ((num1*num2)*num3)/100

but it says Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline operator fun BigDecimal.times(other: BigDecimal): BigDecimal defined in kotlin public inline operator fun BigInteger.times(other: BigInteger): BigInteger defined in kotlin

Actually my code is:

fun onSimpleInterest(view: View) {
        val str:String = txtDisplay.text.toString()
        val sp = arrayOf(str.split("[*+\\-\\/]".toRegex(), 3))
        val num1 = sp[0]
        val num2 = sp[1]
        val num3 = sp[2]
        val simpleInterest = ((num1*num2)*num3)/100
            buttonSI.setOnClickListener {
                txtDisplay.text = simpleInterest

            }

        }

Solution

  • Couple of things going on here.

    The split extension function returns a List. So sp is actually an Array of Lists.

    Since sp's type is an Array of Lists, indexing it (val num1 = sp[0], etc) is actually returning Lists, not Strings. So num1, num2 and num3 are actually List<String>.

    What you need to do is get rid of the arrayOf and just set sp to the result of str.split. Sp will now be a List, so you can set num1, num2 and num3 to the appropriate indices, which will be Strings.

    Next, convert those Strings to Ints, then you can do your arithmetic.

    Finally, simpleInterest is an Int, but I'm pretty sure txtDisplay will expect a CharSequence, so convert that Int back to a String.

    Solution:

    fun onSimpleInterest(view: View) {
        val str:String = txtDisplay.text.toString()
        val sp = str.split("[*+\\-\\/]".toRegex(), 3)
        val num1 = sp[0].toInt() // Possible Exceptions
        val num2 = sp[1].toInt()
        val num3 = sp[2].toInt()
        val simpleInterest = ((num1*num2)*num3)/100
        buttonSI.setOnClickListener {
            txtDisplay.text = simpleInterest.toString()
        }
    }
    

    NOTE: There are many instances here that could throw an exception that you're not catching and handling.

    If a user types less than 3 elements, then the List returned by split will have a size less than 3. So Indexing it (sp[1], etc) could return IndexOutOfBoundsException.

    Also on that same line, even if the user types 3 elements or more, these elements could potentially not be integers. In which case trying to convert them to Ints could return NumberFormatException.

    You should handle these possibilities.