Say I have a scala library that exposes api methods that take scala specific types (say a collection that isn't available in java).
Does this mean you have to either change the exposed parameter, or change the collection to a java compatible type and then iterate over it and initialize the scala specific collection?
Basically what I am getting at is, when designing a scala api that will be used in java, you have to use a compatible type or you pay performance/memory penalty if you have to iterate and map the java collection to the scala one right?
Is that basically what the options are?
From http://www.scala-lang.org/faq/4
What does it mean that Scala is compatible with Java?
The standard Scala backend is a Java VM. Scala classes are Java classes, and vice
versa. You can call the methods of either language from methods in the
other one. You can extend Java classes in Scala, and vice versa. The
main limitation is that some Scala features do not have equivalents in
Java, for example traits.
Also, to answer your question, plase visit How to use scala.collection.immutable.List in a Java code
Related
I was writing some code and was going to throw a RuntimeException as a default for something, when I noticed that there are two options for RuntimeException - one from java.lang and one from kotlin:
Inside the kotlin version of this, there's an entire list of other methods which work the same way :
So, from my understanding of this, the one from package kotlin is simply an alias for the java equivalent (correct me if I'm wrong) which leads me to the question :
what is the point of having this alias file and when should you use it over the "standard" java equivalent ? Does this simply save a few imports ?
When using the JDK, these map to JDK classes. When using Kotlin for Javascript, they would map to a specific implementation in the Kotlin Javascript library. Documentation about actual and expect here.
To answer your question, if there's a chance of you porting your code to also work on another platform, always use the kotlin. variant. Otherwise, it doesn't matter.
In my opinion typealias is strong feature provided by Kotlin language.
Why? Because it gives ability to extend code to multiple domains like extension to provide interoperability between any other languages and Kotlin.
It also becomes helpful when providing APIs or SDK with semantic versioning without worrying much about changes affecting on lower versions of APIs.
One good example would be Collections derived from Java to Kotlin language with some additional & powerful methods as typealias (Literally it saves lot of development time and efforts).
Another good example would be multiplatform programming support by Kotlin language that helps you create APIs with actual and expect keywords implementation.
So long story short, I prefer using RuntimeException from Kotlin package to extend support amongst variety of Kotlin versions (You can see newly added classes starting from version 1.3, but doesn't affect existing API).
I'm developing an open source library in Java and would like to ensure that it is convenient for Java 8 users, and takes advantage of new concepts in Java 8 wherever possible (lambdas etc.)
At the same time I absolutely need to maintain backwards compatibility (the library must still be usable for people using Java 6 or 7).
What useful features from Java 8 can I adopt that would be beneficial for library users without breaking library compatibility for users of older Java versions?
I don't know about your library, this advice might be slightly off.
Lambdas: Don't worry. Any functional interface can be implemented using a Lambda expression.
Method references: Same as lambdas, they should just be usable.
Streams: If this fits your library, you should use them, but keeping compatibility is harder here. The backwards compatibility could be achieved using a second library part, wrapping around the base library and hooking into the public API of it. It could therefore provide additional sugar/functionality without abandoning Java 6/7.
Default methods: By all means, use these! They are a quick/cheap/good way to enhance existing implementations without breaking them. All default methods you add will be automatically available for implementing classes. These will, however, also need the second library part, so you should provide the base interfaces in your base library, and extend the interfaces from the companion-library.
Don't fork the library, abandoning the old one, as there are still many developers who cannot use Java 8, or even Java 7. If your library is sensible to use on e.g. Android, please keep that compatibility.
If you want your code to be usable by Java 6 consuming VMs, you have to write using Java 6 language compatibility. Alas. The bytecode format critically changed from 6 to 7, so code for 7 and 8 won't load into 6. (I found this with my own code migrating to 7; even when all I was using was multi-catch — which should be writable in the 6 bytecode — I couldn't build it for a 6 target. The compiler refused.)
I've yet to experiment with 8, but you'll have to be careful because if you depend on any new Java packages or classes, you will still be unable to work with older versions; the old consuming VMs simply won't have access to the relevant classes and won't be able to load the code. In particular, lambdas definitely won't work.
Well, can we target a different classfile version? There's no combination of source and target that will actually make javac happy with this.
kevin$ $JAVA8/bin/javac -source 1.8 -target 1.7 *.java
javac: source release 1.8 requires target release 1.8
So there's simply no way to compile Java source with lambdas into a pre-Java 8 classfile version.
My general take is that if you want to support old versions of Java, you have to use old versions of Java to do so. You can use a Java 8 toolchain, but you need Java 7 or Java 6 source. You can do it by forking the code, maintaining versions for all the versions of Java you want to support, but that's far more work than you could ever justify as a lone developer. Pick the minimum version and go with that (and kiss those juicy new features goodbye for now, alas).
If you use any new language features in Java 8, it requires also using Java 8 bytecode.
$ javac -source 1.8 -target 1.7
javac: source release 1.8 requires target release 1.8
That means your options are quite limited. You cannot use lambdas, method references, default methods, Streams, etc. and maintain backwards compatibility.
There are still two things you can do that users of Java 8 will benefit from. The first is using Functional Interfaces in your public API. If your methods take Runnables, Callables, Comparators, etc. as parameters, then users of Java 8 will be able to pass in lambdas. You may want to create your own Single-Abstract-Method interfaces as well. If you find you need Functions and Predicates, I'd suggest reusing the ones that ship with GS Collections or Guava instead of writing your own.
The second thing you can do is use a rich collections API that benefits from using Functional Interfaces. Again, that means using GS Collections or Guava. For example, if you have a method that would return List, return MutableList or ImmutableList instead. That way, callers of the method will be able to chain usages of the rich API exposed by these interfaces.
As said by others, providing and using interfaces with a single method such that they can be implemented using lambdas or method references when using Java 8 is a good way of supporting Java 8 without breaking Java 7 compatibility.
This can be complemented by providing methods by your library which fit into one of the standard function types of Java 8 (e.g. Supplier, (Bi)Consumer, (Bi)Function) so that Java 8 developers can create method references to them for Java 8 API methods. This implies that their signature matches one of these functional interfaces and they don’t throw checked exceptions. This often comes naturally, e.g. getFoo() may act as a Function and isBar() as a Predicate but sometimes it’s possible to improve methods by thinking about possible Java 8 use scenarios.
For example, if you provide a method taking two parameters, it’s useful to choose the order where the first parameter is the one that is more likely to be a key in a Map. So it is more likely to be useful for Map.forEach with a method reference.
And avoid method with ambiguous signatures. E.g. if you have a class Foo with an instance method ReturnType bar() and a static method ReturnType bar(Foo) neither of them can be used as method reference anymore as Foo::bar would be ambiguous. Eliminate or rename one of these methods.
It’s important that such methods do not have undocumented internal state that causes surprising behavior when used by multiple threads. Otherwise they can not be used by parallel streams.
Another opportunity that should not be underestimated is to use names for classes, interfaces and members conforming to patterns introduced by the Java 8 API. E.g. if you have to introduce some sort of filter interface with a test method for your library that ought to work with Java 7 as well, you should name the interface Predicate and the method test to associate it with the similar named functional interface of Java 8.
I have to work was a little bit outdated JVM which supports only Java 1.4. I would like to use generics in my code, which is possible according to this article http://www.ibm.com/developerworks/java/library/j-jtp02277/index.html. Unfortunately, Collections classes in our library are not generic and they cannot be replaced (which means I cannot use http://download.oracle.com/otndocs/jcp/jsr14-2.4-ea-demo-oth-JPR/). An obvious solution is to write generic wrappers for all main classes - ArrayList, HashMap, HashSet and create generic interfaces Map, etc. This is quite a work to do, so I am wondering if there might be already a library which provides this functionality.
Can you compile your code for a JVM 1.4?
If your code is compiled for Java5 (6 or 7) you'll probably get a "bad version in class file" -Error.
If you use any compiled library, all have to be compiled for Java 1.4.
After reading some OpenJDK mailinglist entries, it seems that the Oracle developers are currently further removing things from the closure proposal, because earlier design mistakes in the Java language complicate the introduction of the Java closures.
Considering that Scala closures are much more powerful than the closures planned for Java 8, I wonder if it will be possible to e. g. call a Java method taking a closure from Scala, defining a closure in Java and giving it to a Scala function etc.?
So will Java closures be represented like their Scala counterparts in bytecode or differently?
Will it be possible to close the gap of functionality between Java/Scala closures?
I think it's more complicated than assuming there's two groups of stakeholders here. The Project Lambda people seem to be working mostly independently of the Oracle people, occasionally throwing something over the wall that the Project Lambda people find out indirectly. (Scala, is of course the third stakeholder.)
Since the latest Project Lambda proposal is to eliminate function types all together, and just create some sort of fancy inference for implementing interfaces that have a single astract method (SAM types), I foresee the following:
Calling Scala code that requires a Scala closure will depend entirely on the implementation of the Function* traits (and the implementation of traits in general) -- whether it appears to the Java compiler as a SAM (which it is in Scala-land) or whether the non-abstract methods also appear abstract to the JVM. (I would think they currently do look like they're abstract since traits are implemented as interfaces, but I'm know almost nothing about Scala's implementation. This could be a big hurdle to interperability.)
Complications with Java generics (in particular how to expressInt/int/Integer, or Unit/Nothing/void in a generic interface) may also complicate things.
Using Scala functions to implement Java SAMs will not be any different than it now -- you need to create an implicit conversion for the specific interface you wish to implement.
If the JVM gets function types (and Oracle seems not to have eliminated that possibility), it may depend how it's implemented. If they're first class objects implementing a particular interface, then all that Scala needs to do to be compatible is make Function* implement the new interface. If a new kind of type is implemented in the JVM entirely, then this could be difficult -- the Scala developers may wrap them using magic like they currently do for Arrays, or they may create create implicit conversions. (A new language concept seems a bit far-fetched.)
I hope that one of the results of all of this discussion is that all of the various JVM languages will agree on some standard way to represent closures -- so that Scala, Groovy, JRuby, etc... can all pass closures back and forth with a minimum of hassle.
What's more interesting to me is the proposals for virtual extension methods that will allow the Java Collections API to use lambdas. Depending on how these are implemented, they may greatly simplify some of the binary compatibility problems that we've had to deal with when changing Scala code, and they may help to more easily and efficiently implement traits.
I hope that some of the Scala developers are getting involved and offering their input, but I haven't actually seen any discussion of Scala on the Project Lambda lists, nor any participants who jump out to me as being Scala developers.
You would likely be able to do this extremely easily using implicit conversions a la collection.JavaConversions whether or not they come out of the box.
Of course, this is not obviously so, because it may be the case that Java closures are turned into types which get generated by the JVM at runtime - I seem to recall a Neal Gafter presentation saying something along these lines
Note: 5 years later, SCALA 2.12.0-M3 (Oct. 2015) did include this enhancement:
Scala 2.12 emits closures in the same style as Java 8.
For each lambda the compiler generates a method containing the lambda body.
At runtime, this method is passed as an argument to the LambdaMetaFactory provided by the JDK, which creates a closure object.
Compared to Scala 2.11, the new scheme has the advantage that the compiler does not generate an anonymous class for each lambda anymore. This leads to significantly smaller JAR files.
Before re-inventing the wheel, I thought I'd see if anyone is aware of an updated version of something like apache commons-beanutils (basically interested in using reflection-based services for populating and extracting bean values), especially one that supports generics.
I don't believe that there is any current library which allows reflection of Java generics. When Java generics were introduced in Java 1.5, they were implemented in the compiler but were not implemented in the VM. So you have a problem of type-erasure when trying to reflect upon a class which implements generics as the types are only visible at compile time and not at runtime. To see more about this and possible work-arounds, check out:
Super type tokens
Reflecting generics
Scala's way of working around reified types