Home > Blockchain >  How do I use such a line in Kotlin?
How do I use such a line in Kotlin?

Time:10-09

I use Python, but I don't know how it works in Kotlin. This is an example example => exec("""print("hello")""") output => hello

exec("""print("hello")""")    output => hello

CodePudding user response:

Short answer: this isn't practical in Kotlin.

Technically, there may be ways, but they're likely to be far more trouble than they're worth; you're far better looking for a different approach to your problem.

Unlike a dynamic (‘scripting’) language like Python, Kotlin is statically-compiled. In the case of Kotlin/JVM, you run the Kotlin compiler to generate .class files with Java bytecode, which is then run by a JVM.

So if you really need to convert a string into code and run it, you'd have to find a way to ensure that a Kotlin compiler is available on the platform where your code is running (which it often won't be; compiled bytecode can run on any platform with a JVM, and most of those won't have Kotlin installed too). You'd then have to find a way to run the compiler; this will probably mean writing your source code out to a file, starting up the compiler program as a separate process (as I don't think there's an API for calling it directly), and checking the results. Then you'd have find the resulting bytecode and load into the JVM, which will probably mean setting up a separate classloader instance.

All of which is likely to be slow, fragile, and very awkward.

(See these previous questions which cover some of the same ground.)

(The details will be different for Kotlin/JS and Kotlin/Native, but I think the principles are roughly the same.)

In general, each computer language has its own approach, its own mind-set and ways of doing things, and it's best to try to understand that and accept that patterns and techniques from one language don't always translate well into another. (In the Olden Days™, it used to be said that a determined programmer could write FORTRAN programs in any language — but only in satire.)

Perhaps if you could explain why you want to do this, and what sort of problem you're trying to solve (probably as a separate question), we might be able to suggest more natural solutions in Kotlin.

  • Related