Pragya Singla
Pragya Singla

Reputation: 254

Evaluate string expression in kotlin without using script engine

I want to evaluate the string expression without using script engine:

string expression can be like:

"((true&&(!false)||true)&&true)&&true"

Anybody have any idea how this can be done in android using kotlin

Thanks

Upvotes: 3

Views: 2810

Answers (2)

Rahul
Rahul

Reputation: 41

Kotlin Android


app.gradle file

Add a new dependency

dependencies {
    implementation 'net.objecthunter:exp4j:0.4.8'
}

main.kt file

    var value = TextView.text.toString()
    var result = ExpressionBuilder(value).build().evaluate()

Upvotes: 3

Michael
Michael

Reputation: 574

I know my answer will not help you in your case where your string expression contain true, false, &&, ||, ! and (). BUT for those who wants to evaluate mathematical expressions I found this library that handles almost all mathematical operators.

Add it to your project and use it this way

    // In root build.gradle
    repositories {
    maven {
        url  "https://dl.bintray.com/kaendagger/KParser"
          }
    } 

    //Add in the dependencies
    dependencies{
     implementation 'io.kaen.dagger:KParser-jvm:0.1.1'
    }

And then in your code you can do something like this

val parser = ExpressionParser()
val result = parser.evaluate("5+1+cos(PI)-2*2/4")
println(result)

Upvotes: 0

Related Questions