The documentation for Kotlin is now located on the new site. This page is kept for historical reasons
Skip to end of metadata
Go to start of metadata
The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Kotlin is designed with Java-compatibility in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well.

Calling Java code from Kotlin

In this section we describe some details about calling Java code from Kotlin. In most cases, you just use it:

import java.util.* 
 
fun demo(source : List<Int>) { 
  val list = ArrayList<Int>() 
  // 'for'-loops work for Java collections: 
  for (item in source) 
    list.add(item) 
  // Operator conventions work as well: 
  for (i in 0..source.size() - 1) 
    list[i] = source[i] // get and set are called 
}

void-returning methods

If a Java method returns void, it will return Unit when called from Kotlin. If, by any chance, someone uses that return value, it will be assigned at the call site by the Kotlin compiler, since the value itself is known in advance (being Unit.VALUE).

Escaping for Java identifiers that are keywords in Kotlin

Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc. It may happen that some of your favorite Java libraries use these words as names for methods. In this situation you still can call those methods from Kotlin, but you need to escape their names with backticks:

foo.`is`(bar)

Null-safety

Any reference in Java may be null. So, all the Java methods called from Kotlin return nullable references (except for those annotated with @NotNull). This allows Kotlin to keep the guarantee of having no NullPointerExceptions unless they are explicitly thrown by Kotlin code or caused by something inside Java code called from Kotlin.

Consider the following examples:

val list = ArrayList<Int>() // non-null (constructor result) 
val size = list.size() // non-null (primitive int) 
val iterator = list.iterator() // nullable (ordinary method)

Checked exceptions

In Kotlin, all exceptions are unchecked, meaning that the compiler does not force you to catch any of them. So, when you call a Java method that declares a checked exception, Kotlin does not force you to do anything:

fun render(list : List<out Any?>, to : Appendable) { 
  for (item in list) 
    to.append(item.toString()) // Java would require us to catch IOException here 
}

Java generics in Kotlin

Kotlin's generics are a little different from Java's (see Generics). When importing Java types to Kotlin we perform some conversions:

  • Java's wildcards are converted into type projections
    • Foo<? extends Bar> becomes Foo<out Bar>
    • Foo<? super Bar> becomes Foo<in Bar>
  • Java's raw types are converted into star projections
    • List becomes List<*>, i.e. List<out Any?>

Like Java's, Kotlin's generics are not retained at runtime, i.e. objects do not carry information about actual type arguments passed to their constructors, i.e. ArrayList<Integer>() is indistinguishable from ArrayList<Character>(). This makes it impossible to perform is-checks that take generics into account. Kotlin only allows is-checks for star-projected generic types:

if (a is 
List<Int>
) // Error: cannot check if it is really a List of Ints 
// but 
if (a is List<*>) // OK: no guarantees about the contents of the list

Invariant arrays

Arrays in Kotlin are invariant, unlike Java. This means that Kotlin does not let us assign an Array<String> to an Array<Any>, which prevents a possible runtime failure. Neither does it allow us to pass an array of a subclass as an array of superclass to a Java method. In most cases, this should not be a major obstacle, but if one really needs to pass an array in a covariant way, they may cast explicitly.

On the Java platform, having a generic class Array to represent arrays leads to a lot of boxing/unboxing operations. As arrays are mostly use where performance is critical, we introduced a workaround for this issue and defined classes IntArray, DoubleArray, CharArray and so on, which are not related to the Array class and are compiled down to Java's primitive arrays.

Object methods

When Java types are imported into Kotlin, all the references of type java.lang.Object are turned into Any?, for any reference may be used there.

The difference between java.lang.Object and Any is that Any declares fewer functions than java.lang.Object. This is done for elegance and platform-independence. So, all that Any has is toString(), equals(Any?) and hashCode().

toString()

From the programmer's perspective almost nothing changes compared to Java: all the existing toString() implementations work, and when you need a custom toString() for your class, you simply override it:

class A() { 
  override fun toString() : String = "A" 
}

Additionally, there is an extension function toString() that works for nullable references, and returns the string "null" if the receiver is null.

equals()/hashCode()

In Kotlin, == stands for a guarded call to equals(). The expression on the left-hand side must have a method named equals that takes one parameter of type Any? and returns Boolean. Thus, all the Java objects have it out of the box. Like toString(), equals() can be overridden in Kotlin classes and there's an extension function that works on nullable references.

hashCode() has no special operator convention and no support for nullable references (there's no universal default semantics for it).

wait()/notify()

Effective Java Item 69 kindly suggests to Prefer concurrency utilities to wait and notify. Thus, these methods are not available on references of type Any, only on Java objects.

getClass()

To retrieve the type information from an object, one uses the javaClass extension property.

val fooClass = foo.javaClass

Instead of Java's Foo.class, use javaClass<Foo>().

val fooClass = javaClass<Foo>()
finalize()

Any does not declare a finalize() function, so when you really need to override it, this is done "by convention":

class Finalized { 
  fun finalize() { 
    // do something 
  } 
}

Note that there's no override keyword before the function. For JVM this will work as an override, because method signature matches, but for Kotlin there's no override.

clone()

clone() can be overridden by with specifying Cloneable as a supertype:

class MyCloneable : Cloneable { 
  override fun clone(): MyCloneable { ... } 
}

Do not forget about Effective Java Item 11: Override clone judiciously.

Inheritance from Java classes

At most one Java-class (and as many Java interfaces as you like) can be a supertype for a class in Kotlin. This class must go first in the supertype list.

Accessing static members

Static members of Java classes form "class objects" for these classes. One cannot pass such a "class object" around as a value, but can access the members explicitly, for example

if (Character.isLetter(a)) { 
  // ... 
}

Calling Kotlin code from Java

We plan to target more platforms in the future, but currently, Kotlin is only compiled for the Java platform. This means that the compiler generates Java bytecode, and thus the code that we write in Kotlin can be called from Java. There are some concepts in Kotlin that are not available in Java, though. In this section, we briefly describe how these concepts are mapped to Java concepts.

Package-level functions

All the functions and properties declared inside a package org.foo.bar are put into a Java class named org.foo.bar.BarPackage.

package demo 
  class Foo() { 
  } 
 
  fun bar() { 
  }

For the root package (the one that's called a "default package" in Java), a class named _DefaultPackage is created.

Checked exceptions

As we mentioned above, Kotlin does not have checked exceptions. So, normally, the Java signatures of Kotlin functions do not declare exceptions thrown. Thus, if we have a function in Kotlin like this:

package demo 
 
fun foo() { 
  throw IOException(); 
}

And we want to call it from Java and catch the exception:

// Java 
try { 
  demo.DemoPackage.foo(); 
} 
catch (
IOException e
) { // error: foo() does not declare IOException in the throws list 
  // ... 
}

we get an error message from the Java compiler, because foo() does not declare IOException.

To work around this problem, use the [throws] annotation:

[throws(javaClass<IOException>())] fun foo() { 
  throw IOException(); 
}

Null-safety

When calling Kotlin functions from Java, nobody prevents us from passing a null as a non-null parameter. That's why Kotlin generates runtime checks for all public functions that expect non-nulls. This way we get a NullPointerException in the Java code immediately.

Properties

Property getters are turned into get-methods, and setters – into set-methods.

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Jul 21, 2011

    On checked exceptions when calling Kotlin code from Java, could you not just make the compiler automatically put the checked exception into the signature, as this was one of the reasons I switched from using scala to totallylazy (a functional library for pure Java).

    Again it's a shame you went with the 'get' 'set' prefix to property methods, as the 'Bean' standard just adds so much noise. IMHO Scala got that right at least.

    1. Jul 21, 2011

      This way checked exceptions will sneak to every higher order function definitions and after that, effectively any other function in the project, which kind of, defeats the purpose of those annotations.
      Those synthetic getters/setters will only be visible from Java code using Kotlin beans, which is proper thing standing at Java side.
      I'm not the one to lecture you but those "shame"s feels weird.

      1. Jul 21, 2011

        On checked exceptions: yes that is exactly the point, if every method / functions automatically declares the checked exceptions then you ensure Java interop. Having used scala libraries from Java, I have had the bad experience to know that it is incredibly easy to forget about Java interop when writing a scala library and create a method that can't be cleanly called from Java (As you point out in you examples). And it gets even worse if you use reflection and UndeclaredThrowableException start getting thrown.

        On the Bean standard, you are right it is the 'standard' but hey so are checked exception!

        Sorry didn't mean to be inflammatory with 'shame', just I feel a lot of the pain that comes from Scala and Kotlin looks like a reaction to the crazy complexity of the Scala compiler. And it's feels almost perfect from reading this!

        1. Jul 21, 2011

          Anonymous

          Daniel, it's not that simple.  

          1) If you are going to take into account checked exceptions then you need to follow variance rules.  For instance if you override a method you can't declare checked exceptions that aren't compatible with the overridden version.  That means that base classes and interfaces will have to explicitly declare checked exceptions and that seriously limits the value of inferring them.

          2) Higher order functions, e.g. map, may not inherently throw an exception in their implementation but might throw if called using a function that does throw.  So now you need what's called "effect polymorphism", which is basically 'generics' for your effects system (in this case checked exceptions).  Java sorta half asses this with "public <T extends Exception> void doSomething() throws T

          Unknown macro: {...}

          ", but T can't be a list of different exception types.  Effect polymorphism can be found in a language called Disciple.  I recommend looking at it before you decide effect polymorphism a good idea. http://disciple.ouroborus.net/wiki/Language/Overview/EffectSystem

          1. Jul 22, 2011

            Hmmmm, yea I see your points. I think I actually like option 4 listed below!

      2. Feb 11, 2014

        I know it's old, but in case anyone is wondering, the shame thing is just a cultural misunderstanding.  "It's a shame" is just an expression - I would say the word "shame" means something completely different in this context.  As an example, you might say: "it's a shame you didn't bring your swimsuit or we could have gone swimming today".  You are thinking of shame in the sense of: "he felt shame because he did something very bad".  Completely different.

  2. Jul 21, 2011

    Anonymous

    Option 4 to catch checked exceptions in Java that Java doesn't expect

    // utility method threatens to throw but doesn't do anything
    public static <T extends Throwable>
    void mayThrow(Class<T> clazz) throws T {}

    // example usage

    public static void main(String[] args) { try

    Unknown macro: { mayThrow(IOException.class); foo(); }

    catch (IOException e)

    Unknown macro: { System.out.println("Caught exception " + e + "."); }

    }

    More fun stuff on Java and checked exception abuse at http://james-iry.blogspot.com/2010/08/on-removing-java-checked-exceptions-by.html

    1. Jul 23, 2011

      Good point. Thanks! I'll add this to the text above.

    2. Jul 23, 2011

      Could you tell me your name, to mention in the text?

  3. Aug 12, 2011

    Did you do any measurements on how expensive are runtime null-checks?

    1. Aug 31, 2011

      The ones we have in IntelliJ IDEA for @NotNull annotations introduce only negligible overhead.

  4. Aug 31, 2011

    First of all I want to say that this language looks very promissing. While removing most Scala drawbacks it keeps most benifits even simplifying some of them.

    Maybe not the right place but let it be here . Several words on Java interoperability. Java is not only language, but also en ecosystem. It's not only ability to call or to be called from Java code, but also interoperability with existing libraries - application servers, reflection tools and so.

    Points below might be too concrete, this is my small experience in scala-java integration. I hope it might be usefull someway.
    1 JPA.

    • Before 2.8 there were problems with nested annotations and placement (backing field, getter, setter). There is not much information on annotations in this wiki, but are you going to support Java-compatible annotations? (There were several words on annotations being more powerfull with allowing to place them in more places, but at least those, which could be translated to Java's one should be translated).
    • If you want Option... write your getter/setter, because Hibernate would never understand your Option type (well it would but it's much much easier to forget it, and it still not works for relations). It seems that this problem shouldn't be in Kotlin as there is not run-time Option here.
    • If you want collections... again you either write getter/setter which would wrap java.util.List-s or use implicit converters all over your code. As JPA knows nothing about scala.Seq.

    Again not a problem, just some extension methods which could make java.util.List and company good citizens in Kotlin collections framework.

    2. Some "transparent primitive" glitches. i.e.

    Again it's not a large problem, but some reflection utilities fail here. I couldn't propose good solution here but this might be used somehow in Kotlin reflection, with something like javaType().

    3. Some problems were with GWT, beside that it doesn't know anything about Scala, it also doesn't know anything about Scala libraries, so again you have to use java collections in RPC. Another point to good wrapping of java collections.

    I'm really only at start of JEE so there might be other glitches.

    As soon as some Kotlin prototype would be available, it would be very interesting to try to evaluate this with some sort of real application. Waiting for this moment with a lot of optimism and impatience .

    1. Aug 31, 2011

      Thank you for your interest in Kotlin!

      To comment on the points you made:

      • We'll do our best to make annotations compatible
      • Collection wrappers will be provided
      • In Kotlin Int means Java's int, and Int? means java.lang.Integer, and generics are properly reified, so the problem of primitives is unlikely to arise
      1. Sep 06, 2011

        Anonymous

        I'm a bit confused about primitive types and generics. It has been said that Kotlin will not support primitives as type arguments in V1, and you just stated that Int corresponds to Java's int, and Int? to java.lang.Integer. However, I see many examples in this wiki where Int is used as a type parameter, e.g., ArrayList<Int>. Should this not be ArrayList<Int?> instead? Is it legal to declare an ArrayList<Int>, and if so, what exactly are you getting? Is it actually a list of java.lang.Integer instances?

        I do not think primitive types and their boxed counterparts should be interchangeable. Scala's Int makes no distinction between the int primitive and java.lang.Integer, and that drives me crazy--it's more difficult to figure out when and where boxing operations occur. I think implicit boxing assignments should be legal, e.g., you should be able to assign an Int value to a Int? variable. However, it should be consistently clear that Int refers to an unboxed primitive while Int? refers to a boxed java.lang.Integer.

        1. Sep 07, 2011

          Kotlin allows Int as a type argument. In this case values are qutomatically boxed.

          Any variable or value of type Int refers to an unboxed integer, and any value of type Int? refers to a boxed integer.

          1. Sep 08, 2011

            I think that is quite misleading, since generics are not actually specialized for primitive types. Given that Int corresponds to an unboxed int primitive, it's natural to assume that a List<Int> is specialized for int primitives when, in reality, it is specialized for the java.lang.Integer class (actually, that isn't true either, but it behaves that way). It's not obvious that a boxing operation is performed every time an Int is passed into or returned from a method or property on a List<Int>.

            While Java does not specialize generics for primitive types either, the aforementioned confusion is avoided because Java expressly prohibits using primitives as type arguments. Developers are likely to assume (incorrectly) that generics are specialized for primitives for a couple reasons.

            First, Java forbids primitive types from being used as type parameters precisely because Java generics only work with class types. Since Kotlin is also a JVM language, it stands to reason that the rules regarding type parameters would be the same if Kotlin generics suffer from the same weakness (i.e. not supporting specialization for primitive types). Since the rules are different (primitives can be used as type arguments), many will assume that the behavior is also different.

            Second, and more importantly, JetBrains claims that generic types in Kotlin are reified. From what I can tell, Kotlin merely emulates reified generics. Considerable effort has been made to ensure that Kotlin generics look and behave like reified generics, but this is an illusion. A very well-crafted and worthwhile illusion, mind you, but an illusion nonetheless. As far as the JVM is concerned, a List<Int> instance and a List<String> instance share the same underlying type. If Kotlin generics were truly reified, List<Int> and List<String> would be distinct types, even though they are based on the same generic template. While the Kotlin language and compiler may treat them as distinct types, the JVM does not. Type parameter information is retained for Kotlin generics, but it is captured at the instance level rather than the type level. The availability of this type information serves to "hide" many shortcomings of type erasure in the JVM, e.g., you can write the equivalent of T.class. The Kotlin language also imposes stricter rules regarding conversions and assignment compatibility of generic types, and these rules can actually be enforced. As a result, the presence of type erasure is very well hidden, but it is still present. While Kotlin allows you to declare generic types with primitive arguments, this is only possible by guaranteeing that the necessary boxing operations occur transparently. In a platform with truly reified generics (like .NET), there would be no need for such boxing operations. If you claim that Kotlin generics are reified, then many developers (especially .NET developers) will incorrectly assume that generics are properly specialized for all types, including primitives. It would be more accurate to describe Kotlin generics as something like "generics with retained type information" rather than "reified generics".

            I encourage you to remember the pit of success. Avoid any design decisions which invite your users to make erroneous assumptions.

            1. Sep 08, 2011

              1. What are bad implications of developers assuming that generics are specialized for primitives?
              2. Why are there no bad implications of Java developers assuming that classes are specialized at all?
              3. Is your second point about favoring the meaning of the term "reified generics" that's natural for .NET people over other meanings that are natural for other groups of people? If yes, why?
              1. Sep 08, 2011

                Anonymous

                1. The issue which comes to mind is boxing and its implications for performance. Assuming I understand correctly, an Int would be automatically boxed as an Int? when added to a List<Int> and unboxed when retrieved. How many unexpected (un)boxing operations might occur when sorting a List<Int> with 100,000 items? A million? A billion?
                2. In Java, there would be some type safety issues and possible unchecked conversions, though it's not a huge issue since the role of type erasure is fairly well publicized. Kotlin seems to have avoided most of those issues, though there may still be potential issues I haven't considered related to the fact that type erasure still exists, hidden as it may be.
                3. No, my point is that describing Kotlin generics as 'reified' is at best debatable and at worst simply wrong. It's arguable whether or not the label is technically correct, but it's also somewhat irrelevant; developers are going to make assumptions based on their understanding of the term. It doesn't help that proponents of Kotlin will undoubtedly draw parallels between Kotlin's support generics and C#/.NET's while contrasting them to Java. It will be easy to overlook the important detail that Kotlin generics are not specialized for primitive types.
                1. Sep 08, 2011

                  1. The same happens in Java, and I didn't hear anyone complaining about this (apart from general complaints about being unable to specialize collections).
                  2. This is like any other abstraction, I suppose...
                  3. I believe that most Java people do not hear "specialization for primitives" when we say "reified generics". So, I think that the trade-off here is the following: a clumsy term versus a term that is debatable for .NET people.
                  1. Sep 08, 2011

                    1. The difference is that Java does not allow you to declare generic types with primitive type arguments, and Kotlin does. It is reasonably obvious that boxing operations occur for a List<Integer>; it would not be obvious if the same occurred for List<int>, which I imagine is why Java does not allow such declarations. Kotlin has overcome many of the shortcomings of Java generics, and it's easy to mistakenly assume that it has also overcome the lack of primitive specialization simply because such declarations are legal (in contrast to Java).
                    2. Indeed.
                    3. There are undoubtedly different takes on what "reified generics" really means. My understanding has always been that all type information is preserved. Reification happens at the type level (not the instance level). Generic types with bound type parameters are reified as specialized types. For an ArrayList<T> with a backing T[] array, the reified type ArrayList<Int> is necessarily different from ArrayList<String>, with the former having a backing Int[] array, a get method returning an Int value, an add method accepting Int value, and so on. This is not simply a case of binding information being preserved; it is the creation (reification) of entirely new specialized types based on the type arguments. As such, there would be no need for implicit boxing or unboxing operations for an ArrayList<Int>. This is not how generics work in the JVM, whether they were written in Java or Kotlin. In Kotlin, the type parameter information is retained, but it only serves to identify the concrete types to which the generic parameters were bound at the declaration site. It does not affect the runtime type. ArrayList<T> is not reified as ArrayList<Int>; in reality, ArrayList<Int> does not even exist. ArrayList<T> exists, and for an instance declared as ArrayList<Int>, the knowledge that T was bound to Int is retained. This is not true reification; it is simply the capture and retention of generic type parameter bindings. Elegant language and compiler design enables Kotlin generics to effectively masquerade themselves as reified generics (with a couple important differences), and the result is a much improved developer experience compared to Java. I do not mean to downplay the engineering significant of your work in this area, but it is important for developers to have a clear understanding of how their code actually behaves.
                    1. Sep 08, 2011

                      1. My take on this is that Kotlin does not have any primitive types at all. Kotlin's Int happens to be compiled to Java's int, but it's an implementation detail.
                      3. Yes, I see what you mean when you say "reification". I am even ready to agree that this is the "right" interpretation of the term. I really admire the fact that you understand so clearly what you mean by this term. But my perception is that such a clear understanding is more of an exception in the world around us.

                      Anyway, thanks for raising the issue. I think I'll do some polling to find out if other people are likely to be mislead the way you describe.

                      1. Sep 08, 2011

                        My take on this is that Kotlin does not have any primitive types at all. Kotlin's Int happens to be compiled to Java's int, but it's an implementation detail.

                        Ah, well, that certainly changes things. Scala has similar treatment of "built-in" types, but it has always bothered me.

                        There are significant differences between Java's primitive types and their boxed counterparts (e.g. int vs. Integer). The primitive types benefit from being light weight and stack-resident, but they have no capabilities other than to hold a value. You cannot, for instance, call methods on them. Java primitives lack the elegance of .NET value types, which can declare methods, implement interfaces, etc., but retain the benefit of being lightweight. It's admittedly somewhat annoying not being able to call compareTo directly on a Java int.

                        Languages like Scala and Kotlin try to "unify" primitive types with their boxed counterparts, which lifts the restrictions from primitive types, but this can only be done with transparent boxing operations. An unfortunate consequence is that it is often difficult to determine when and where boxing is occurring, as you may not know whether an Int is actually an int primitive or an Integer. I have to wonder if there isn't a "better" solution, though I've yet to think of one .

                        1. Sep 08, 2011

                          I would be really interested in a better solution, too )

                2. Sep 08, 2011

                  To clarify, my concerns boil down to one issue:

                  My initial expectation of how generics behave in Kotlin, which is based on the information published here, differs significantly from the actual behavior. The semantics subtly imply that code behaves in one way, and those implications are reinforced by the documentation, but in reality the behavior is quite different. This is contrary to the "pit of success".

                  I can understand the value of generics with primitive type parameters, even if the generic types are not specialized for those primitive types; it is useful to be able to declare a List<Int> where it is guaranteed that everything which comes out of the list is non-null (by virtue of the fact that only non-nullable Int values could have gone in). But this feature of convenience can lead developers to mistakenly believe that generics with primitive type arguments are actually specialized for those types. The information published here reinforces that notion by describing Kotlin generics as 'reified', and the burden was on me to ask for clarification about the actual behavior.

                  If you are going to allow primitive types to be used as generic type arguments, then I implore you to adjust your documentation. Rather than stating that Kotlin supports reified generics, state instead that Kotlin mimics reified generics, with some important differences (e.g. transparent boxing of primitives, instance-level overhead, etc.). Point out those issues clearly such that the information sticks with the reader. That way, when developers start getting really excited and start blogging about this awesome new JVM language, they'll be able to describe the features and behavior more accurately, and there will be less risk of developers writing code based on an incorrect understanding of the language. The accuracy of information breaks down as it is passed from one person to another, and if the original source is unclear, then misinformation becomes rampant .

                  1. Sep 08, 2011

                    I think my previous comment (which, I guess, I was writing while you were writing this one ) pretty much answers this one too. There are no primitive types in Kotlin. But I'll ask around to find out if other people may be confused. Thanks again.

  5. Oct 07, 2011

    Typo: Foo<? extends Bar becomes Foo<out Bar>

    Should be: Foo<? extends Bar> becomes Foo<out Bar>

    1. Oct 08, 2011

      Fixed. Thanks

  6. Oct 14, 2011

    Typo: backtics, should be backticks.

    1. Oct 14, 2011

      Fixed. Thanks

  7. Jan 15, 2012

    Typo: realted.

    1. Jan 15, 2012

      Fixed. Thanks

  8. Jan 15, 2012

    What are your plans for "finalize()"?  Given its generally unhelpful behavior (not being a destructor, issues with revivifying, no guarantee to ever be called, etc.) do you plan to provide a better behaved alternative?

    1. Jan 15, 2012

      Currently, I don't see any reasonable thing we could possibly do about it.

  9. Jun 13, 2012

    While trying to get Vertx running from Kotlin, I was stumped by this one:

    in java:

    server.requestHandler (new Handler<HttpServerRequest> () {

         public void handle (HttpServerRequest req) {

             System.out.println ("handled")

         }
    }

    Furthest I got in Kotlin (but still NOT working):

    server?.requestHandler (object: Handler<HttpServerRequest> {

         public override fun handle (req: HttpServerRequest?): Unit {

             println ("Handled")

         }

    }

    1. Jun 14, 2012

      Please, report this to our issue tracker and provide some information on what exactly is not working. Thanks!

  10. Jun 14, 2012

    Andrey: thank's for responding, actually I got this working, I was missing a "?", ie:

    Handler<HttpServerRequest> should have been Handler<HttpServerRequest?>

    So, I have Vertx + Guice in Kotlin, pretty sweet!

    Unrelated to this post (but seeing as I have your attention):

    Couple of Groovy features missing from Kotlin:

    1) Object literals (like JSON) - not sure if you have this or not, 'object' seems to be overloaded significantly.

    2) ability to initialize an object by passing an attribute map (or object literal) into the constructor.

    3) ability to reference an object using .with{} - this one could potentially be an 'extension' to Any.

    Any chance we can expect some/all of these?

    1. Jun 14, 2012

      1) Object literals: I believe, named arguments and/or builder cover this
      2) Impossible in a static language
      3) with() is a library function in Kotlin

      1. Jun 14, 2012

        1) Object literals:

        just learned that this works, which is GREAT.

            (had to google around to find out about it):

        val o = object {
            val name = "Fred"
            val arr = array (1,0)
        }

        however, this would get the bonus points:

        val o =  {
             val name = "Fred"
              val arr =  [1,0]
        }

        any chance of that?

        can't the compiler infer object and array  keywords in these circumstances??

        2) Constructor initialization: 

        I guess you can't just look up the fields by reflection because you have that 

        initialization block to deal with too.

        3) with():

        Where is '.with()' can't seem to find it (and googling 'with' doesn't help much!)

        Thanks for the prompt reply. Am a potential big fan, having tried to use:

        Scala - too complex, too slow compilation, and poor idea support (with the exception ofIJ)

        Groovy - too untyped, runtime performance

        Fantom - nice, but some java interop issues.

        New question:

        to convert to JSON I've been using Jackson,

        but, given that you've already got a Kotlin to Javascirpt bridge,

        can't you just provide a toJSON() call on any object (again,

        you must have this already on your json side).

        1. Jun 14, 2012

          1) with(): Sorry, I was wrong, the function is not added to the library yet, it can be defined as follows:

          fun <T> with(t : T, f : T.() -> Unit) { 
            t.f() 
          }

          and used as follows:

          with(foo) { 
            bar() // bar is a member of foo 
          }

          2) JSON

          This is not so straightforward to define, I think. There will be tricky cases with loops in the reference graph etc.
          But some kind of this functionality would be desirable for JS integration

          1. Jun 14, 2012

            1) with():

            That's exactly what I was looking for, you are a super quick responder.

            I'd vote for adding that to the library asap, as you can chain functions without polluting code with intermediary variables.

            2) JSON: yes circular references are an issue, but there are various de-facto solutions out there.

            Also, you can add use @JsonIgnore.

            At any rate, if you're going to generate Javascript then you have to have some solution here, no avoiding that.

  11. Jun 14, 2012

    Discovered an interesting feature.

    If you want to execute a method if an object IS null, then this works:

    null ?: {println ("a is null")}();

    Even better would be if this worked:

    null ?:  println ("a is null")

    ie: can't you infer that the operand on the right of the elvis is a function with no argements,

    and simply call it?

    1. Jun 14, 2012

      To return something, you have to call it. So this construct does exactly what you want.

      1. Jun 14, 2012

        yep, figured that out and edited my post (would be nice if this wiki used markdown

        instead of macros)

  12. Jun 14, 2012

    Andrey, looking carefully at you 'with()' function it's not exactly what I had in mind.

    Groovy:

    similar to '.each()' in Groovy, but for one object.

    (I'm assuming that Kotlin has an '.each()'  - does it? )

    1. Jun 21, 2012

      You mean that you need to call it with a dot instead of saying with(...) {...}?

      Then, you define it as an extension function:

      fun <T> T.with(f : (T) -> Unit) { 
        f(this) 
      }
      1. Jun 21, 2012

        Actually no, what I'm asking about is something that Xtend calls a "with operator", see below, from their page:

        http://www.eclipse.org/xtend/new_and_noteworthy/index.html

        also note their features page, they seem to bit somewhat ahead of Kotlin, in many of these features, and also have much less noisy builder syntax:


        With Operator Since M7

        A new operator '=>' has been added to the language and a corresponding extension method for java.lang.Object on the left hand side and a lambda expression on the right hand side. The with operator allows you to write:

        new JTextField => [
              text = 'My Text'
        ]

        Think of it as a let-expression, which allows for binding any object to the scope of the block, in order to do side-effects in it. Very handy when initializing objects.

        1. Jun 21, 2012

          What's the difference with "with" above?

  13. Jun 14, 2012

    Problem with JSON serialization (Andrey where should I post this)?

    Fails with this error:codehaus.jackson.map.JsonMappingException:
    No serializer found for class Kotlin101.Objects.Constructors.namespace$main$2 and
    no properties discovered to create BeanSerializer (to avoid exception,
    disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS)
    now, if we add the configuration:

    

    Then we get:

    {}

    David

    1. Jun 15, 2012

      Andrey - any ideas on this JSON problem?

      How do you currently serialize object literals to json?

      1. Jun 21, 2012

        I'm not aware about any particular work on JSON so far. Feel free to contribute!

        1. Jun 21, 2012

          I'm not grokking this.

          You have full javascript interop, ie: Kotlin -> Javascript, correct?

          Yet, you can't convert kotlin to JSON?

          How is that possible? Please explain.

    2. Jun 21, 2012

      Forum works well for questions like this: http://devnet.jetbrains.com/community/kotlin

      We'll need to investigate why this fails. Maybe, in byte code the properties become private in this case (which is wrong).

      Feel free to submit a bug

  14. Sep 07, 2012

    About @NotNull

    I doubt if relying on a proprietary annotation is going to make you many friends, even if the library can be shipped freely.

    There are too many libraries out there that do not use it, but are still null safe. I would like to propose to allow the !! symbol in declarations:

    fun f(a: X!!)

    asking the compiler to insert a null pointer check at the call, to make sure a is not null. This would be equivalent to:

    This can be useful when Kotlin code overrides functions from Java or for any Kotlin code called from java.

    1. Sep 07, 2012

      This would be equivalent to Java's approach: no guarantees.
      We use external annotations to provide nullability information for libraries not under our control.

      1. Sep 08, 2012

        Why would this not be a guarantee? If the compiler inserts a null check, then either an exception is thrown or when the body of the function starts non null is asserted.

        1. Sep 10, 2012

          If I'm not missing anything, this is exactly what Java does: it checks for null at every call site, and throws an exception.

          1. Feb 10, 2013

            Not exactly.I think you might be missing, that my suggestion would only require Null checks, at the beginning of the Kotlin method.

            So they are executed once when the method is entered.

            The check would happen once at the earliest possible moment, and then no more null checks are needed after that.

            Kotlin code would remain safe (and clean!). Java would remain as it is.

            This would very much simplify my Kotlin development work.

            1. Feb 12, 2013

              As of M5, Kotlin generates not-null assertions at method entry points and at Java method call sites. See this blog post

  15. Dec 15, 2012

    Hey Andrey,

    If I create a class object or just an object in kotlin, how could I use it in Java? I think that the Class.object.$instance is not a good point and object is a reserved key word.

    This is a feature that is not interoperable with kotlin and java?

    (I still think that object instances should be exported like static instances in java or be implemented like a proxy to an existent instance)

    1. Dec 17, 2012

      Objects are exported as static variables to Java:

      works for me, and also shows up in completion. Does it work for you?

  16. Feb 27, 2014

    for functions with default value, such as :

    public fun subscribeIntent(topic: String = "#", qos: Int = 0) : Intent {
    val intent = Intent()
    intent.setAction(ACTION_SUBSCRIBE)
    intent.putExtra(PARA_TOPIC, topic)
    intent.putExtra(PARA_QOS,qos)
    return intent
    }

    how to call it in Java; It seems that I can't call like this:

       subscribeIntent()

    1. Feb 27, 2014

      Java does not support default arguments, so there's no way to call such functions other than passing all the arguments

  17. May 11, 2014

    for lambda functions with Unit as a returing value, such as :

    public object DataBus {
    public fun subscribe(topic: String, handler: (msgReceived: Any) -> Unit) {
    }
    }

    how to call it in Java; It seems that I can't call like this:

    DataBus.instance$.subscribe("log", new Function1<Object,Void>() {
    @Override
    public Void invoke(Object msg) {
    Log.instance$.v(TAG, msg.toString());
    }
    });

    1. May 11, 2014

      It seems works:

      DataBus.instance$.subscribe("log", new Function1<Object, Unit>() {
      @Override
      public Unit invoke(Object msg) {
      Log.instance$.v(TAG, msg.toString());
      return Unit.VALUE;
      }
      });

  18. Jun 24, 2014

    I need help to understand Java Object arrays. I.e. Object[]. I have a Java-function declaration returning an Object[] and I want to implement it with a Kotlin function. Idea and the compiler want the signature: fun values(): Array<Any>

    Why Any and not Any?  ?

    And how do I fill this return value with the values coming when a java map as declared Map<*, *>  was passed in?

    1. Jun 24, 2014

      This is an unsound simplification we temporarily make in Kotlin: any generic arguments are not-null by default. This will be changed soon.

      You can annotate your Java method with @KotlinSignature("fun values(): Array<Any?>") to override this default

    2. Jun 24, 2014

      Another option is to create an array of Any? and shamelessly cast it to Array<Any> at the end of your function