Home > Enterprise >  Kotlin // Solve the example in a line
Kotlin // Solve the example in a line

Time:10-19

How to solve an example in a string? Let's say we have val example : String = "3 5"

So how do I solve this example? Or if val example : String = "3*5/3"

CodePudding user response:

Two ways to achieve it:

  1. Keval - 3rd party dependency

    You can either use Keval.eval("(3 4)(2/8 * 5) % PI") or as an extension function on String, "(3 4)(2/8 * 5) % PI".keval(). This will return the calculated value as Double. For your example, "3*5/3".keval().

    To use it, add implementation("com.notkamui.libs:keval:0.8.0") in dependencies in app level build.gradle file and sync gradle. Then, use it in any file as mentioned in the above para, put the cursor on the line and press Alt Enter (or hover for suggestions) to import the necessary imports.

    Look into its Readme.md on the provided link for more usage and implementation details.

  2. Custom String parsing using BODMAS rule

    You can split the string using the BODMAS rule, parse the split array as int/double, if it throws exception, it means the substring is an expression too, again split it using BODMAS, parse and perform the calculation.

  • Related