Kotlin Introduction - mariamaged/Java-Android-Kotlin GitHub Wiki

Kotlin - Introduction

Kotlin/JVM

  • Kotlin's compiler would create Java bytecode from the Kotlin source code, such as Java's compiler creates Java bytecode from Java source code.
  • The resulting bytecode can be used java and similar tools, regardless of whether it was written in Java, Kotlin, or something else.
     
  • While Android does not use the JVM, the same basic mechanism is applied:
    • Kotlin's compiler generates Java bytecode, which the Android build process then converts into Dalvik bytecode for use in Android apps.

Kotlin/JS

In 2014, Kotlin/JS was introduced.

  • This allows Kotlin's compiler to "compile" Kotlin source code into JavaScript source code, with an eye towards the code being used in an environment like NodeJS.

The JavaScript that you get from the compilation process is not necessarily going to be easily readable by ordinary humans, but that's not the goal.

Kotlin/Native

  • More recently, the Kotlin team has added Kotlin/Native.
  • This compiles Kotlin code to native opcodes, the same as you might find with a C/C++ compiler.
  • In particular, Kotlin/Native is designed to generate code that can run on iOS and macOS, interoperating with Objective-C.

Kotlin/Common

  • Kotlin/Common is the term given to a type of library that limits itself to using Kotlin classes and functions that exist for all Kotlin runtime environment.

Kotlin/Multiplatform

  • It is a way of setting up a project such that some core app logic is written in a Kotlin/Common library, while other "modules" are set for specific runtime environments.

Getting Kotlin, Normally

  • For many developers, you will not need to download and install a Kotlin environment, as that will be handled by your IDE or other build tools.
     
  • For example, Android Studio users get Kotlin "for free" as part of building Android-Studio based projects.
    • Kotlin's toolchain - compilers, etc. - are obtained in the form of a Gradle plugins, coupled with some Kotlin support "baked into" Android Studio itself.

The REPL Tool

For many Android Studio projects, you can go to Tools > Kotlin > Kotlin REPL to bring up a dedicated REPL in its own pane.

You can type in Kotlin code and click the green Run toolbar button in the tool to execute that code:

enter image description here

Scratch Files as REPL

Your project can contain "Scratches", or scratch files.

These are found in a "Scratches and Consoles" section of the project tree.

  • You can create Kotlin script files (.kts) there and bring them up in an editor.
  • With the "use REPL" checkbox checked, you can click the green Run button in the editor's toolbar to run your script and show the output side by side with it.
     

enter image description here
  enter image description here

Installing Kotlin and its REPL

Another option is to actually download and install Kotlin, which includes a REPL.

  • The Kotlin site documents how to download and install their command-line compiler.
Windows Linux and macOS
Your only option is to download a ZIP file from Kotlin's GitHub release area and unZIP it, with the bin/ directory in the output being a directory that you would want to add to your PATH environment variable. Can use the ZIP approach too, but they also have a variety of other options (SDKMAN!, Homebrew, MacPorts, Ubuntu snaps).
  • Running the kotlinc-jvm command by itself will bring up the REPL, where you can type an expression and gets the results:
     

enter image description here
 

  • Alternatively, you can put your Kotlin into a plain text file ending in .kts.
  • Then, use kotlinc -script to compile and run your Kotlin, without having to mess with an IDE and project.
  • For example,
kotlinc -script hello.kts

A few "Hello, World!" Examples

Basic
println("Hello, world!")
Wrapped in a Function
fun main(args: Array<String>) {
	println("Hello, world")
}
  • The main() function works similarly to the static main() method in a Java program.
Wrapped in a Class
class HelloWorld {
	fun speak() {
		println("hello, world)
}
}
HelloWorld().speak()
  • In try.kotlinlang.org, while the class is fine, you need to wrap the HelloWorld().speak() in a main() function.
class HelloWorld {
	fun speak() {
		println("Hello, world")
}
}

fun main(args: Array<String>) {
	HelloWorld().speak()
}

Breaking it Down

  • "Hello, world!": looks much like strings in Java, Ruby, JavaScript and many other programming languages.
    • Kotlin strings are a but more powerful than those in Java, as Kotlin adopted some of the string features offered in other programming languages.

Basic Types and Expressions

Basic Types and "Objectness"

From Kotlin's standpoint, everything is an object.

  • This stands in contrast to some languages, like Java, where basic types are "primitives" but have object counterparts.

Numbers

Kotlin supports the same basic numeric types as does Java.

  • Byte (8-bit representation).
  • Short (16-bit representation).
  • Int (32-bit representation).
  • Long (64-bit representation).

And there are two-floating point types:

  • Float (32-bit representation).
  • Double (64-bit representation).

Number Literals

Sometimes, you will use numbers directly into your code, as literal values, such as 1234 or 3.14159.

  • By default, this will be an Int and a Double, respectively.
    • If you want to make a literal be a Long, add an L suffix
    • If you want a floating-point literal be treated as a Float, not a Double, append f to the number.
println(1234::class)
  • Prints class kotlin.Int
println(1234L::class)
  • Prints kotlin.Long
println(3.14159::class)
  • Prints kotlin.Double
println(3.14159f::class)
  • Prints kotlin.Float

Here, the ::class syntax says "give me a reference to the Kotlin class for this object".

  1. For longer numbers, if you like, you can use underscores for the "thousands separator".
println(1_234)
  • Gives you 1234.
  1. For integral types, the default representation is in decimal format.
    • You can define literals in hexadecimal by using an 0x prefix (0xFFA4C639).
    • You can also define binary literals by using an 0b prefix (0b10110100).

Mathematical Representation

  • + for addition.
  • - for subtraction.
  • * for multiplication.
  • / for division.
  • % for the remainder after division ("modulo").

Parentheses can be used for grouping to offer manual control over the order of operations.

The default order of precedence puts multiplicative operations (*, /, %) higher than additive operations (+, -).

println(1+2*3)
  • Prints 7.
println((1+2)*3)
  • Prints 9.

Boolean

  • Kotlin offers a Boolean type, with two values: true and false.
    • && for a logical AND.
    • || for a logical OR.
    • ! for a logical NOT.

Strings

  • Kotlin offers two string quoting options: double quotes and triple quotes.
  1. Double-quoted strings works like its Java counterpart:
    • It cannot contain newlines.
    • Special characters, such as newlines or tabs, need to be indicated via "escape sequences".
    • There are eight escape sequences supported in Kotlin:
      • \t for tab.
      • \b for backspace.
      • \n for newline.
      • \r for "carriage return".
      • \' for a single quote.
      • \" for double quotes.
      • \$ for dollar sign.
      • \\ for a backslash.
    • Anything else can be encoded using Unicode escape sequences (e.g., \u221E for the infinity symbol).
  • Triple-quoted "raw" string: does not support escape sequences but does support embedded newlines, tabs, and anything else.
    • This allows you to directly express strings that otherwise would be a mess of text and escape sequences, resulting in more readable code.
println("""Hello World,
	world!"""")
  • However, indents then become a problem.
  • If your IDE wants to indent code to keep things aligned, it might add spaces or tabs inside of your string that you do not want.
  • To help with this, you can use trimMargin() function on String to eliminate unwanted indentation.
    • Each line is inspected, and if the line starts with whitespace followed by the margin prefix that you passed to trimMargin() (>).
    • The whitespace and margin prefix are removed.
    • If you do not pass any margin prefix to trimMargin(), the default prefix is |.
println("""Hello,
	>world!""".trimMargin(">"))
Hello,
World

String Expressions

String concatenation works using the + operator as you would expect.

  • However, you will find a lot less string concatenation used in Kotlin than you may be used to in other languages like Java.
  • That is because Kotlin supports, like Ruby, supports "string interpolation", where expressions embedded in String literals can be evaluated directly.
println("Hello, " + "world!")

Characters

  • In Kotlin, as in Java, a Char literal is represented by a single-quoted character:
println('a')
  • Also, similar to Java, escape sequences can be used for individual characters, much as they can be with strings.
⚠️ **GitHub.com Fallback** ⚠️