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.
Related
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.
I didn't find any explanation in the reference, but when I type impl in IntelliJ IDEA, I get an error:
It seems that it's treated as a reserved word, but what's it for?
I tried putting many kinds of stuffs after impl but I get the error every time.
Update: It's renamed to expect after Kotlin 1.2.
It's for future multiplatform project support, and it's the pair of the header keyword which #hotkey explained in their comment here. It appeared in one of Andrey Breslav's presentations which you can find here, this specific topic starts at the 14:25 mark.
To sum it up briefly, the basic idea he presents is that you could have a common module shared between your platforms, in which there are some functions that are declared but not implemented, and are marked with the header keyword. Then, for the different platforms (JVM, JS, etc) you could have separate modules that implement these functions in platform specific ways - these actual implementations are where the impl keyword would be used.
He says that this whole system is just an internal prototype for now, so this presentation is probably all the public info we have about it. I'd also be interested in more details about this mechanism though :)
Update: as of the Kotlin 1.2 Beta, these keywords have been now replaced with expect and actual.
Kotlin functions marked with inline keyword are, well, inlined during the compilation and it seems that code coverage tools (like JaCoCo) fail to properly calculate code coverage. What is the usual approach to overcoming this issue? Is there a way to make the test somehow avoid the inlining step and invoke the tested methods directly? Is it possible to skip report generation of all inlined methods (via Gradle task, for example) without excluding whole classes?
I don't believe it is possible to turn off inlining since some functions may not make any sense if they are not inlined. These include functions with reified types (since the inlining creates the availability of type information) and functions with lambdas as parameters, since they can affect the control flow of the method they are inlined in.
There is the bug in the JetBrains Java Coverage tools, see https://youtrack.jetbrains.com/issue/KT-12605 .
So, just wait until bug will be fixed (or vote on it, to speedup development)
Kotlin team has introduced the Kover plugin with the goal of supporting all language constructs including inline functions.
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.
is it possible to write an AspectJ pointcut that matches the usage of a specific operator with a specific type?
Some background information: I'm working on a project where we have to use a legacy Java library (pre 5.0, before the enum keyword) which comes with several "pseudo-enum" types, i.e. normal Java classes that define static constants of its own type. Those "feel" very much like enums, but using them like enums can result in an error. Therefore I'd like AspectJ to mark uses of == with objects of one of these types as an error, if that is possible. I have googled this and consulted the normally very helpful book AspectJ in action, but so far without success. Any help is appreciated.
== is not the same as equals(), and is implemented by the JVM, and as far as I can tell cannot be modified by aspectj. Also, I don't think that AspectJ is the correct tool for this job.
A better approach would be to implement a Checkstyle rule or similar for your project to allow you indicate these points. You could have them as errors or warnings. See Writing Checks for Checkstyle for more information.
This would require some coding, but so would the aspectJ solution.
Checkstyle has an eclipse plugin as well as a maven plugin, so you could have these errors appearing as you work in the IDE.