Kotlin Introduction - mariamaged/Java-Android-Kotlin GitHub Wiki
- Kotlin's compiler would create
Java bytecodefrom theKotlin source code, such as Java's compiler creates Java bytecode from Java source code. - The resulting bytecode can be used
javaand 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 processthen converts intoDalvik bytecodefor use in Android apps.
- Kotlin's compiler generates Java bytecode, which the Android
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.
- 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
iOSandmacOS, interoperating withObjective-C.
- Kotlin/Common is the term given to a
type of librarythat limits itself to usingKotlin classes and functionsthat exist forall Kotlin runtime environment.
- 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.
- 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 Studiousers get Kotlin "for free" as part of building Android-Studio based projects.-
Kotlin's toolchain- compilers, etc. - are obtained in the form of aGradle plugins, coupled with some Kotlin support "baked into" Android Studio itself.
-
For many Android Studio projects, you can go to
Tools > Kotlin > Kotlin REPLto 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:
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.
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:
- Alternatively, you can put your Kotlin into a
plain text fileending in.kts. - Then, use
kotlinc -scriptto compile and run your Kotlin, without having to mess with an IDE and project. - For example,
kotlinc -script hello.ktsprintln("Hello, world!")fun main(args: Array<String>) {
println("Hello, world")
}- The
main()function works similarly to the staticmain()method in a Java program.
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 amain() function.
class HelloWorld {
fun speak() {
println("Hello, world")
}
}
fun main(args: Array<String>) {
HelloWorld().speak()
}-
"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.
From Kotlin's standpoint, everything is an object.
- This stands
in contrastto some languages, like Java, where basic types are "primitives" but haveobject counterparts.
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).
Sometimes, you will use numbers directly into your code, as literal values, such as
1234or3.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".
- For longer numbers, if you like, you can use underscores for the "thousands separator".
println(1_234)- Gives you 1234.
- For integral types, the default representation is in decimal format.
- You can define literals in
hexadecimalby using an 0x prefix (0xFFA4C639). - You can also define
binary literalsby using an 0b prefix (0b10110100).
- You can define literals in
- + 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.
- Kotlin offers a Boolean type, with two values:
trueandfalse.- && for a logical AND.
- || for a logical OR.
- ! for a logical NOT.
- Kotlin offers
two string quoting options:double quotesandtriple quotes.
-
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, andanything 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 tabsinside 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 prefixthat you passed totrimMargin() (>). - The whitespace and margin prefix are removed.
- If you do not pass any margin prefix to
trimMargin(), the default prefix is|.
- Each line is inspected, and if the line starts with whitespace followed by the
println("""Hello,
>world!""".trimMargin(">"))Hello,
WorldString 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!")- 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.