Search code examples
javakotlinjvm

Kotlin operators in, it, is,


I'm a rookie with Kotlin and I can't differ between these three operators, do they have any relation between them? How's their comparison with Java?


Solution

  • No, there's no direct connection between them, other than being 2-letter keywords in Kotlin.

    They're used for different things:

    • in is used to test whether one object is contained within another (syntactic sugar for contains() in Java):

      if (someObject in someList) …
      

      It's also used when iterating through a collection (where Java just uses :):

      for (item in someList) …
      

      And to specify that a type parameter is contravariant (where Java would use ? super):

      interface List<in E>
      
    • it is used within a lambda that takes exactly one parameter, to refer to the parameter in a concise way without having to give it a name (with no direct Java equivalent):

      someList.filter{ it < 10 }
      
    • is is used to test whether an object is of a given type (the same as instanceof in Java):

      if (s is String) …
      

    As @Adrian says, all the keywords are explained in the Kotlin reference documentation.