How to compile and use Kotlin code in runtime? - kotlin

I'm trying to create a Kotlin Vert.x language support module and I need a way to compile Kotlin files and load the results with a ClassLoader. I've tried using kotlin-compiler library and found K2JVMCompiler class, but it seems to support only command-line-style arguments with its exec method. Is there a way to compile a Kotlin file in runtime (possibly without having to save and read .class files) and immediately load the generated classes? (Kind of like Groovy does.) If not, do you have any useful compiler arguments suggestions or pretty much any advices?

This feels like an XY Problem. You want to know how to compile Kotlin on the fly so that you can more easily use Vert.x by running from Kotlin source files instead of compiled code. But really the recommended path for Vert.x usage is to create a simple bit of code that deploys your verticle within compiled code.
In the question, your link for language support says Vert.x 2 in the path "vertx.io/vertx2/language_support.html"; which is different than how it is now done in Vert.x 3. I think you are merging two thoughts into one. First that Vert.x 3 wants you to run Java/Kotlin files from source (it doesn't really; that was a Vert.x 2 thing they moved away from for compiled languages), and second that you need custom language support (you don't).
You should try to use Vert.x 3 by running compiled code. To do so, build your classes and run your own main() that deploys a verticle programatically. Your code would be simple as:
import io.vertx.core.Vertx
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
vertx.deployVerticle(SomeVerticleOfMine())
}
Alternatively, the docs for running and deploying from the command-line say:
Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going!
And really it is indeed just for prototyping and quick testing, and it isn't any faster than letting your IDE do the same and running from the compiled classes. You also then have debugging features of the IDE which are infinitely valuable.
For a few helper libraries for using Kotlin with Vert.x, view these options:
Vert.x 3 module for Klutter - I am the author, one of my libraries
Vert.x 3 helpers for Kotlin - by Cy6erGn0m
Kovert, a REST framework for Vert.x 3 - I am the author, one of my libraries
Vert.x nubes - not Kotlin specific, but makes Vert.x-Web friendlier for JVM languages.
There is a full sample project of running Vert.x + Kovert (specifically start with the App class). You can look at the code of Kovert to do your own similar work of starting and running Vert.x nicely, with Promises or however you wish. The docs for Kovert have links to code for starting Vertx and also starting a Verticle to use Vert.x-Web, so more sample code you can read. But it helps to understand Injekt (light-weight dependency registry), Kovenant (promises library), and Klutter configuration injection to understand the complete sample.
Other quick note, Vert.x has codegen support for other languages, but since you can call all of the Java version directly, it does not need to support Kotlin either.

Kotlin 1.1 comes with javax.script (JSR-223) support, which means you can use it as scripting engine similarly to JavaScript with Nashorn.

Related

How do I use such a line in Kotlin?

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
Kotlin supports JSR-223. You can use the jvm scripting engine to eval kts files.
val engine = ScriptEngineManager().getEngineByExtension("kts")
engine.eval("""print("hello")""")
You need JSR-223 library dependency. Refer to example
implementation("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")
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.

Rust IDE not detecting Result from error_chain, thinks I'm using the std::result::Result

I have an errors.rs file with error_chain! {}, which exports Result, ResultExt, Error and ErrorKind.
If I use self::errors::*, IntelliJ thinks that I'm using the default Result (std::result::Result, I think). However, if I explicitly import the types using use self::errors::{Result, ...}, everything works out hunky dory.
I can tell because the standard result has two type params, but the error_chain one has only one.
In either case, it still compiles.
I'm using the standard Rust IntelliJ plugin, version 0.1.0.1991.
Help! Does anyone know how to get the plugin to understand what the macro is doing?
The IntelliJ-Rust plugin uses its own code parser. It allows to leverage all the IntelliJ platform capabilities (like code navigation, formatting, refactoring, inspections, quick documentation, markers and many others) but requires implementing all the language features, which is not a simple task for Rust (you can find a more in-depth discussion of the Rust compiler parser versus IDE parser in this reddit post).
Macros expansion is probably the biggest language feature that is not supported by the plugin parser at the moment. That is, the plugin sees this error_chain! call, can resolve it to its definition, but doesn't expand it to the actual code and hence doesn't know about the new Result struct that shadows the one from stdlib. Unfortunately, in some cases it leads to such false positive error messages.
I've converted this error annotation into an inspection, so in the next plugin version you'll be able to switch it off entirely or for the particular code block. The work on macros expansion is also in progress.

Why didn't Kotlin follow Java syntax?

I'm in the process of learning Kotlin as an Android developer!
Out of curiosity, why didn't the JetBrains guys follow the Java style syntax (where they could have), and made it easier on developers to learn Kotlin?
For example, defining a simple function in Kotlin:
fun simpleFunc(x: Int): Int {
// do stuff
}
Why didn't they do:
fun Int simpleFunc(Int x) {
// do stuff
}
I would appreciate hearing your opinion on this
As mentioned in the Kotlin FAQ, Kotlin's syntax makes it more natural to omit type declarations when they can be inferred by the compiler (which isn't supported by Java). Also, from our experience with Kotlin, we see no evidence that Kotlin's type declaration syntax presents a difficulty for people learning Kotlin.
(Note that your suggested syntax is also different from Java, so it's not clear why you think it would be easier to learn.)
Java is like a coffee, and Kotlin means that coffee with a little bit sugar in there. In some cases, Kotlin does increase the efficiency and make the programming more enjoyable.
Comparing with Java, Kotlin is more effective and actually can work with Java pretty well.
Check the example in that picture here about Safe Calls on the official kotlinlang.org,
In Chains, when there's a null value,you need to use if function to determine whether the value is null,but there's only one sentence method needed for Kotlin.
Plus, when you are using Gradle daemon and Smart Compilation,Kotlin shows a faster compile speed than Java.
the horizontal axis means ten consecutive incremental builds with one core file changed.
You can see that the Gradle daemon still takes two or three runs to warm up, but after that the performance of both languages is very similar. With no changes, Java takes 4.6 seconds per warm build, while Kotlin averages 4.5 seconds. When we change a file that isn’t used by any other files, Java requires an average of 7.0 seconds to do a warm build, and Kotlin clocks in at 6.1. And finally, when we change a file that is imported by many other files in the project, Java requires 7.1 seconds to do an incremental build once the Gradle daemon is warmed up, while Kotlin averages 6.0 seconds.
Citations: 1. https://kotlinlang.org/docs/reference/null-safety.html
https://medium.com/#johnkorly/kotlin-vs-java-performance-drill-down-which-to-choose-2514bdf91916
The kotlin team describes here why the type declarations (like in your example) are on the right:
Why have type declarations on the right?
We believe it makes the code more readable. Besides, it enables some nice syntactic features. For instance, it is easy to leave type annotations out. Scala has also proven pretty well this is not a problem.

Is there a way to mix MonoTouch and Objective-C?

I'd like to know if there is a way to mix C# and Obj-C code in one project. Specifically, I'd like to use Cocos2D for my UI in Obj-C and call some MonoTouch C#-Library that does some computations and get some values back. Is there a way to do this? Or maybe the other way around, i. e. building in MonoTouch and calling Cocos2D-functions?
Thanks.
The setup that you describe is possible, but the pipeline is not as smooth as it is when you do your entire project in MonoTouch. This is in fact how we bootstrapped MonoTouch: we took an existing Objective-C sample and we then replaced the bits one by one with managed code.
We dropped those samples as they bitrot.
But you can still get this done, use the mtouch's --xcode command line option to generate a sample program for you, and then copy the bits that you want from the generated template.m into your main.m. Customize the components that you want, and just start the XCode project from there.
During your development cycle, you will continue to use mtouch --xcode
Re: unknown (google):
We actually did this as described.
See this page for a quick start, but the last code segment on that page is wrong, because it's omitting the "--xcode"-parameter.
http://monotouch.net/Documentation/XCode
What you have to do to embed your Mono-EXE/DLL into an Objective-C program is to compile your source with SharpDevelop, then run mtouch with these parameters:
/Developer/MonoTouch/usr/bin/mtouch --linksdkonly --xcode=output_dir MyMonoAssembly.exe
This only works with the full version of MonoTouch. The trial does not allow to use the "--xcode"-argument . The "--linksdkonly"-argument is needed if you want mtouch to keep unreferenced classes in the compiled output, otherwise it strips unused code.
Then mtouch compiles your assembly into native ARM-code (file extension .s) and also generates a XCode template which loads the Mono-Runtime and your code inside the XCode/ObjC-program. You can now use this template right away and include your Obj-C-code or extract the runtime loading code from the "main.m"-file and insert it into your existing XCode-project. If you use an existing project you also have to copy all .exe/.dll/.s files from the xcode-output-dir that mtouch made.
Now you have your Mono-Runtime and assembly loaded in an XCode-project. To communicate with your assembly, you have to use the Mono-Embedding-API (not part of MonoTouch, but Mono). These are C-style API calls. For a good introduction see this page.
Also the Mono-Embedding-API documentation might be helpful.
What you have to do now in your Obj-C-code is to make Embedding-API calls. These steps might involve: Get the application domain, get the assembly, get the image of the assembly, locate the class you want to use, instantiate an object from that class, find methods in class, call methods on object, encapsulate method arguments in C-arrays and pass them to the method-call, get and extract method return values.
There are examples for this on the embedding-api-doc-page above.
You just have to be careful with memory consumption of your library, as the mono runtime takes some memory as well.
So this is the way from Obj-C to C#. If you want to make calls from C#/Mono into your Obj-C-program, you have to use the MonoTouch-bindings, which are described here.
You could also use pure C-method calls from the embedding/P/Invoke-API.
Hope this gets you started.
Over the weekend it emerged that someone has been porting Cocos2D to .NET, so you could also do the whole work on .NET:
http://github.com/city41/CocosNet
Cocos2D started as a Python project, that later got ported to Objective-C, and now there is an active effort to bring it to C#. It is not finished, but the author is accepting patches and might be a better way forward.
Calling Objective-C from MonoTouch definitely looks possible. See the Objective-C selector examples
What library are you calling? Perhaps there's an Objective-C equivalent.

Can I run JUnit 4 to test Scala code from the command line?

If so, how? I haven't come across the proper incantation yet.
If not, what's the best approach to unit-testing Scala code from the command line? (I'm a troglodyte; I use IDEs when I have to, but I prefer to play around using Emacs and command-line tools.)
Since compiled Scala is just Java bytecode (OK, with a lot more $ characters in class names), it would be exactly as for running JUnit 4 tests against Java code, i.e. from the command line by passing the test classes as arguments to org.junit.runner.JUnitCore. As JUnit 4 out of the box only has command line support, you don't even have to worry about suppressing GUI based test runners.
That said, the specific Scala test frameworks (ScalaTest, ScalaCheck) do provide a more idiomatic set approach to testing code written in this more functional language.
You may be interested in ScalaTest.
ScalaTest is a free, open-source
testing tool for Scala and Java
programmers. It is written in Scala,
and enables you to write tests in
Scala to test either Scala or Java
code. It is released under the Apache
2.0 open source license.
Because different developers take
different approaches to creating
software, no single approach to
testing is a good fit for everyone. In
light of this reality, ScalaTest is
designed to facilitate different
styles of testing.
See the Runner documentation for how to run tests from the command line.
The suggestion of ScalaTest -- or any of the other Scala-specific frameworks, for that matter, is very good. I'd like to point to something else, though.
SBT.
SBT is a build tool, like Ant, Maven or Make. One interesting aspect of it, which will matter to us, is that it is Scala-based. I don't mean it has special capabilities to handle Scala code or that it is written in Scala, though both these things are true. I mean it uses Scala code, instead of XML like Maven and Ant, as the configuration source.
That in itself is interesting. Just today I saw a wonderful example of separating test sources from program sources, which I post here just because its so cool.
// on this project we keep all sources, whether they be Scala or Java, and whether they be
// regular classes or test classes, in a single src tree.
override def mainScalaSourcePath = "src"
override def mainJavaSourcePath = "src"
override def testScalaSourcePath = "src"
override def testJavaSourcePath = "src"
override def mainResourcesPath = "resources"
// distinguish main sources from test sources
def testSourceFilter =
"Test*.scala" | "Test*.java" |
"AbstractTest*.scala" | "AbstractTest*.java" |
"ScalaTestRunner.scala"
def mainSourceFilter = ("*.scala" | "*.java") - testSourceFilter
override def mainSources = descendents(mainSourceRoots, mainSourceFilter)
override def testSources = descendents(testSourceRoots, testSourceFilter)
But what makes it even more interesting is that SBT works like a console. You run "sbt", and you get dropped into a console-like interface, from which you can type commands like, for instance, "test", and have your tests run.