Can an integer in Kotlin be equal to an math expression?

岁酱吖の 提交于 2021-01-01 09:25:35

问题


I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:

val input = "2+2"
input.toInt()

回答1:


Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt function can only parse a String containing a single whole number (it's just a wrapper for Integer.parseInt).

If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.




回答2:


No you can't.

You can like this:

val a = "2"
val b = "2"
val c = a.toInt() + b.toInt()

Or

val input = "2+2"
val s = input.split("+")
val result = s[0].toInt() + s[1].toInt()



回答3:


This can be done with the kotlin script engine. For details see Dynamically evaluating templated Strings in Kotlin

But in a nutshell it's like this:

val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)



回答4:


No, Integer cannot be equal to math expression.

You may use String Templates

Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string.

A template expression starts with a dollar sign ($) and consists of either a simple name:

  val i = 10
  val s = "i = $i" // evaluates to "i = 10"


来源:https://stackoverflow.com/questions/45094181/can-an-integer-in-kotlin-be-equal-to-an-math-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!