Skip to end of metadata
Go to start of metadata

Define a package

package my.demo // One per file 
 
import std.io.* 
 
// ...

See Packages.

Define a function

// Return type mandatory 
fun sum(a : Int, b : Int) : Int { 
  return a + b 
}

or

// Return type may be inferred 
fun sum(a : Int, b : Int) = a + b

When no meaningful value returned:

fun printSum(a : Int, b : Int) : Unit { 
  print(a + b) 
}

or

// Return type is optional when Unit is intended 
fun printSum(a : Int, b : Int) { 
  print(a + b) 
}

See Functions.
See Hello, world!.

Define a local variable

Assign-once (read-only) local variable:

val a : Int = 1 
val b = 1 // Type is inferred 
val c : Int // Type required when no initializer provided 
c = 1 // definite assignment

Note that semicolons are optional.

Mutable variable:

var x = 5 // Type inferred 
x += 1

See also Properties And Fields.

Use a string template

fun main(args : Array<String>) { 
  if (args.size == 0) return 
 
  print("First argument: ${args[0]}") 
}

See String templates.
See Arrays.

Use a conditional expression

fun max(a : Int, b : Int) : Int { 
  if (a > b) 
    return a 
  else 
    return b 
}

or

// 'if' is an expression 
fun max(a : Int, b : Int) = if (a > b) a else b

See if expressions.

Null-checks

A reference must be explicitly marked as nullable to be able hold a null:

package multiplier 
 
// Return null if str does not hold a number 
fun parseInt(str : String) : Int? { 
  // ... 
} 
 
fun main(args : Array<String>) { 
  if (args.size < 2) { 
    print("No number supplied"); 
  } 
  val x = parseInt(args[0]) 
  val y = parseInt(args[1]) 
 
  // We cannot say 'x * y' now because they may hold nulls 
 
  if (x != null && y != null) { 
    print(x * y) // Now we can 
  } 
}

or

// ... 
  if  (x == null) { 
    print("Wrong number format in '${args[0]}'") 
    return 
  } 
  if  (y == null) { 
    print("Wrong number format in '${args[1]}'") 
    return 
  } 
  print(x * y) // Now we know that x and y are not nulls

See Null-safety.

is-checks and automatic casts

The is operator checks if an expression is an instance of a type (and more). If we is-checked an immutable local variable or property, there's no need to cast it explicitly to the is-checked type:

fun getStringLength(obj : Any) : Int? { 
  if (obj is String) 
    return obj.length // no cast to String is needed   
  return null 
}

or

fun getStringLength(obj : Any) : Int? { 
  if (obj !is String) 
    return null 
  return obj.length // no cast to String is needed 
}

See Classes and Inheritance.
See Type casts.

Use a for-loop

fun main(args : Array<String>) { 
  for (arg in args) 
    print(arg) 
 
// or 
 
  for (i in args.indices) 
    print(args[i]) 
}

See for-loops.

Use a while-loop

fun main(args : Array<String>) { 
  var i = 0 
  while (i < args.size) 
    print(args[i++]) 
}

See while-loop.

Use pattern-matching

fun cases(obj : Any) { 
  when (obj) { 
    1          -> print("One") 
    "Hello"    -> print("Greeting") 
    is Long    -> print("Long") 
    !is String -> print("Not a string" 
    else       -> print("Unknown") 
  } 
}

See Pattern matching.

Use ranges and in

Check if a number lies within a range:

if (x in 1..y-1) 
  print("OK")

Check if a number is out of range:

if (x !in 0..array.lastIndex) 
  print("Out")

Check if a collection contains an object:

if (obj in collection) // collection.contains(obj) is called 
  print("Yes")

Iterate over a range:

for (x in 1..5) 
  print(x)

See Ranges.

Use function literals to filter and map collections

names filter {it.startsWith("A")} sortby {it} map {it.toUpperCase()} foreach {print(it)}

See Higher-order functions and Function literals.

What's next

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

    Anonymous

    Any thoughts on using something other than val & var?  To me they are too similar in name.  Obviously this is what Scala uses but I think keywords that are different by more than one letter would be better.

    1. Jul 21, 2011

      Any suggestions?

      1. Jul 21, 2011

        Anonymous

        "let" is relatively widespread for the purpose of denoting immutable variables (ML/F#, Haskell etc), and it's also what's going to be used in JavaScript, so perhaps that.

        By the way, does Kotlin provide any way to declare a variable within a limited scope other than body of a loop or branch of a conditional? In Java you can just use { } to introduce a new scope at any point, but in Kotlin that would be a Unit-returning function literal, no?

        1. Jul 21, 2011

          No, if you have a {...} that is not assigned or passed anywhere, it's just a block, like in Java

          1. Jul 21, 2011

            Anonymous

            I've actually realized that I didn't see anywhere in the docs whether Kotlin has expression/statement separation, or only expressions (some being of types Unit or Nothing)? We know that "if" is an expression, but what about "while", "try" etc?

            If everything is an expression, then what is the type and value of a free-standing block - Unit, or the type & value of last expression computed in the block? If the latter, then (to clarify) can I write:

            ?

            1. Jul 21, 2011

              In Kotlin, there are expressions and declarations. Expressions have type, in particular loops, and ifs with one branch have type Unit.

              A stand-alone block is a block that's not assigned to anywhere. In your example, the thing in curly braces becomes a function literal.

              1. Jul 21, 2011

                Anonymous

                Got it. But then it would parse as a ():Unit typed block, so I can apply it in place, right?

                1. Jul 21, 2011

                  Yes, but using the run function seems nicer to me:

                  val x = run { ... } 
                   
                  fun run<T>(f : fun() : T) : T = f()
                  1. Aug 03, 2011

                    A stand-alone block is a block that's not assigned to anywhere. In your example, the thing in curly braces becomes a function literal.

                    var f = if (true) { 10 } else { 20 };

                    f - function????

                    1. Aug 03, 2011

                      No. None of the blocks is assigned anywhere in this example. Only if-expression is.

                      1. Aug 03, 2011

                        Hm.

                        var f = if (true) { 10 } else { 20 };

                        common grammar:
                        val f = if (true) trueExpresion else falseExpression;

                        trueExpression/falseExpession are blocks ?? Why f is not block ?

                        other example

                        var f2 = if (true) ({ 10 }) else ({ 20 });

                        now f2 - function???

                        1. Aug 03, 2011

                          It's not about grammar The type checker decides whether an expression in curly braces is a block or not.

                          var f2 = if (true) ({ 10 }) else ({ 20 });

                          In this case f2 has a function type

        2. Jul 21, 2011

          Anonymous

          It doesn't appear that Kotlin makes a preference on mutable versus immutable... F# which does prefer immutability uses:

          let and let mutable.  This would obviously make mutable variables more verbose to write.

      2. Jul 22, 2011

        Anonymous

        We use 'const' and 'var' in our JS-like scripting language.

        The word 'const' is fairly obvious and distinct looking from 'var'.

        You could always use 'final' if you wanted to be more Java-like.

      3. Aug 10, 2011

        Anonymous

        make it

        var

        +var

        when plus indicates a constant

        1. Aug 12, 2011

          The initial request was to make them different in more than one letter

      4. Nov 02, 2011

        Anonymous

        Grace language uses "def" for constants (including functions) and "var" for variables. I think it's good when functions/methods are treated similar to other constants.

    2. Jul 21, 2011

      Anonymous

      of course the similarity is quite useful when refactoring between var and val.... ;)

  2. Jul 20, 2011

    Anonymous

    Ah! Thanks for pointing it out, I had not understood what the difference was between immutable and mutable...

  3. Jul 21, 2011

    Anonymous

    If you must specifiy "val" before any variable declaration, just change it so that it is

    Int a = something

    var  a = something

    its more consistent and preferable IMHO 

    1. Jul 21, 2011

      Anonymous

      using var a : Int = something is desirable because it makes the type annotation optional and allows it to be inferred.  Although Int a = something is common in many mainstream languages doesn't really make it better.  At least not when type inference is a big feature of the language.  And btw. type annotations can be very verbose with more advanced type system features like generics. ex: List<Map<Foo, Bar<Baz>>>

  4. Jul 21, 2011

    Anonymous

    Please tell me you'll fix this

    if( x > 0)

      dosomething;

    Braces should never be optional.

    1. Jul 21, 2011

      Anonymous

      What!?  Require braces?  I disagree.  Expressiveness is sometimes achieved by being compact.  The only argument one can present for this is to avoid bugs introduced by adding code after and forgetting or not realizing that there are no braces.  If your code sucks (like mine) then make sure it is bug-free by testing it thoroughly.

    2. Jul 21, 2011

      Anonymous

      Keep in mind that if/else is an expression in Kotlin - requiring braces for that use case doesn't make sense.

  5. Jul 21, 2011

    Anonymous

    Idea has excellent autocomplete functionality, and it seems that Kotlin will get that excellent support from the beginning, so the length of the reserved words usde by the language itself is not a problem.

    Modern computers have insane amounts of hard drive space and memory, and 5 more characters per word will not make a difference.

    So, is there any reason for "var" abbreviation instead of the normal word "variable"? The same goes for "val", but in that case i can understand while the word "value" is not a good candidate for the reserved word, but it is not related to time required to type two more characters or to extra space required to store two more characters.

    1. Jul 22, 2011

      Anonymous

      The same goes for "fun" instead of "function", and all other ugly abbreviations if there are more =)

  6. Jul 26, 2011

    Anonymous

    why not

    val a :Int = 1
    val b :    = 1
    

    instead of 

    val a :Int = 1
    val b      = 1 
    

    IMO 'val b:=1' is more constent than 'val b=1' because the former looks similar to 'val a:Int=1' but the latter doesn't. 

  7. Jul 29, 2011

    Anonymous

    Cool, but please change "fun" to "def"!

    1. Sep 02, 2011

      Anonymous

  8. Sep 07, 2011

    Anonymous

    And as someone said before: Please make "val" "const". It's really more obvious and easier to read.

    1. Jun 06, 2012

      I agree that const communicates the intention of declaring an immutable value better than val, plus it's clearly distinct from var.

      The only drawback I see in const is that it's not as short as val. That may be an issue. As someone pointed out, it is important to stress immutability as a preference, so declaring immutable values should ideally be less verbose than declaring mutable variables.

      Maybe def could do the trick? Could we use def for defining both immutable values and functions? That would be somewhat Groovy-like, I guess.

      1. Jun 06, 2012

        The problem is that "def" means nothing in particular.

        1. Jun 06, 2012

          I think co-existance of val and var keywords are really confusing part of Scala & Kotlin syntax. ML's let looks way better than val.

          1. Jun 06, 2012

            ML's let won't work for class' members (properties), though.

        2. Jun 29, 2012

          I guess you're right. How about this then:

          • val name         /* immutable */
          • mutable name   /* mutable */

          That would be foolproof, clearly distinguishable AND clearly in favor of immutability.

          1. Jul 02, 2012

            Something along these lines makes sense, although there's a small problem:

            • val is a noun (value)
            • mutable is an adjective
  9. Sep 14, 2011

    Anonymous

    #1. +1 on val to const. The point of "val" to be a assign-once is a bit questionable. 99.9% of the time these values will be assigned at declarations (normal use-case for constants). 0.1% of the time, you would like to declare this and then give it a value 3-4 lines later (can't think of why but nevertheless let's assume that you need to do that). Why not "finalise" a variable in that case at the point of assignment. e.g.

    var c :Int

    final c = x

    #2. "fun" is a proper english word, abbreviations never work in computer languages in my opinion. Developers are keyboard wizards, they can type "function" in no time, no need to appreviate. Perhaps "define" or "method" are other considerations.

    1. Sep 14, 2011

      abbreviations never work in computer languages in my opinion

      Very popular ones that definitely work:
      int — C/C++, Java, Scala, ...
      char — C/C++, Java, C#, ...
      var — Pascal, JavaScript, Scala, ...
      enum — C/C++, C#, Java, ...

      Some more that work all right:
      def — Scala, Groovy, ...
      const — C/C++, Pascal, ... <-- You vote for using this abbreviation
      struct — C/C++, C#, ...
      bool — C/C++, C#, ...

      1. Sep 14, 2011

        Anonymous

        I like fun a lot better than def Let's say is more fun

        1. Oct 13, 2011

          Anonymous

          mos' def go with def in place of fun