- Multiparadigm language
- Statically Typed
- Compiles to java & javascript
"I'll teach you java, let's learn hello world". First word is public. What's public? then static. What's static?.
There's a lot of stuff "you don't need to know right now". Kotlin doesn't make its problems your problems.
fun main() {
println("Hello world")
}
# compile
kotlinc-jvm hello.kt
# run
kotlin HelloKt
# or run with...
java -classpath . HelloKt
kotlinc-jvm
runs a REPL. .kts
files are Kotlin script, so you don't even need to declare a function.
Nice things:
- semicolon is optional - nice for DSLs especially
- sensible warnings
- type inference - generally don't declare variable types.
- val vs var - simple constants
- string templates & multiline strings
- positional params & named args, can mix
- variable sized argument lists
- destructuring - bind multiple variables in a single statement
- loop variables are always val, as are function parameters. Constructors are an exception, declaring var makes the property settable
- Argument matching - using
when
when
is a statement but also an expressionin
as a clause ofwhen
egin 13..19
-> "teen"to identify types
is String -> "it's a string"` - Java 8 introduced
Optional<T>
. Problem is you're returning a union object, overhead in memory plus you can always return null for an optional. In KotlinT?
is the nullable version of type T. - Elvis operator
?:
for handling nullables safely with minimal syntax
Using infix
operators you can write DSLs like this, it
is a context argument, left
, fast
, right
are receivers.
operate {
it turns left
it runs fast
it turns right
}