Kotlin Iniciante

dlard707
12.7K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

In this section you'll find some basics syntax to start coding with Kotlin.

Variables

Kotlin provides two way to declare variable.

  • Immutable (read-only) variable:

Using the keyword valmeans that your variable could be assign just once.

immediate assignment

val a: Int = 1

variable's type can be inferred

val b = 2 // `Int`

deferred assignment

val c: Int  // type is required when there is no initializer
c = 3
  • Mutable (read/write) variable:

Using the keyword var allow you to declare mutable variables.

String templates

String are made easier with Kotlin, more convinient to use, and more readable.

Simple templates

Here is a more interesting part. You may be able to invoke piece of code inside a template, avoiding lots of boilerplate code.

String manipulation

Math expression

Control expressions

if statement becomes an expression

To compare two values, you would write the following code

In Kotlin, if can be an expression, that means that you can assign a variable or return the if directly. Previous snippet can be write as follow.

Or, in idiomatic Kotlin (c.f. part 3. on Functions)

fun max(a: Int, b: Int) = if (a > b) a else b
when expression

If you were familiar to the switch statement from other language like Java, you won't find it in Kotlin. It has been replaced by the when expression.

You can use when to evaluate objects and return a result.

To go further, when allow you to make some condition by mixing values, ranges, Types, etc. The when expression will try to match with every branches sequentially and stop at the first satisfied condition.

A third one, you can use when without any input value, like in this snippet.

when {
  obj1 is Person -> goToRestaurant()
  obj2 is Animal -> feedTheDog()
}

Loops

For loops

for works on anything that's iterable. You may think of it as a foreach, like in Java's lambda or C#.

A combination of Kotlin's features, makes for even more convinient. By desctructuring we can iterate over a collection with indexes:

While loops

while works as in many languages

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content