Kotlin intro
Anton Rutkevich
GDG Minsk
Yandex
About me
- Use Java, Groovy, Kotlin
- For Android, Google App Engine
- Main project is a library
Who's there? :)
- What languages do your use?
- What projects do you develop?
What do you not like in Java?
- No 'module' access level
- No lambdas (unless you use Java 8)
- No properties; much boilerplate (Lombok)
- String concatenation
- *Utils classes
- easy to write non-safe code
- non-final by default
- nullable dy default
Why new language?
Java is good, but hard to change due to backward compatibility
Main goals
- To create a Java-compatible language,
- That compiles at least as fast as Java,
- Make it safer than Java
- Make it more concise than Java
- And make it way simpler than the most mature competitor – Scala.
Basics
Variables
/* Read-only */
val a: Int = 1
// `Int` type is inferred
val b = 1
// Type required when no initializer is provided
val c: Int
/* Read-write */
var x = 5 // `Int` type is inferred
x += 1
Functions basics
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum(a: Int, b: Int): Int = a + b
when
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")
}
}
Classes
Definition
class Invoice
class Customer(val customerName: String)
class Customer(name: String) {
{
logger.info("Initialized with ${name}")
}
}
Classes can contain
- Functions
- Properties
- Nested and Inner Classes
Inheritance
open class Base {
open fun canBeOverridden() {}
fun notOverrideable() {}
}
class Derived() : Base() {
override fun canBeOverridden() {}
}
No statics
(class objects instead)
class C {
class object {
fun create() = C()
}
}
fun main() {
// C denotes the class object here
val c = C.create()
// can be a value
val cClassObject = C
}
Traits
(Interfaces)
trait MyTrait {
val property: Int // abstract
fun bar()
fun foo() {
// optional body
print(property)
}
}
Nested & Inner classes
class Outer {
private val bar: Int = 1
class Nested {
fun foo() = 2
}
}
class Outer {
private val bar: Int = 1
inner class Inner {
fun foo() = bar
}
}
Visibility modifiers
- private — visible only in the declaring scope and its subscopes (inside the same module);
- protected — (applicable only to class/trait members) like private, but also visible in subclasses;
- internal — (used by default) visible everywhere within the same module (if the owner of declaring scope is visible);
- public — visible everywhere (if the owner of declaring scope is visible).
Properties definition
var <propertyName>: <PropertyType> [= <property_initializer>]
<getter>
<setter>
public class Address {
public var name: String = ...
var stringRepresentation: String
get() = this.toString()
set(value) {
// parses string into this object
setDataFromString(value)
}
}
Backing fields
// the initializer value is written
// directly to the backing field
var counter = 0
set(value) {
if (value >= 0)
$counter = value
}
// no backing field
val isEmpty: Boolean
get() = this.size == 0
Backing properties
// backing property
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null) {
// Type parameters are inferred
_table = HashMap()
}
return _table ?: throw AssertionError("Set to null by another thread")
}
Null-safety
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val l = a.length() // valid
val m = b.length() // error: variable 'b' can be null
// safe casts
b?.length()
// Elvis!
val n = b?.length() ?: -1
Advanced Functions
Extensions
(as *Utils alternative)
fun MutableList<Int>.swap(x: Int, y: Int) {
// 'this' corresponds to the list
val tmp = this[x]
this[x] = this[y]
this[y] = tmp
}
val l = mutableListOf(1, 2, 3)
// 'this' inside 'swap()' will hold the value of 'l'
l.swap(0, 2)
Resolved statically!
Lambdas
// function that takes lambda
fun synchronized(lock: Lock, body: () -> Unit): Unit {
lock.lock()
try {
body()
} finally {
lock.unlock()
}
}
// usage
synchronized (lock) {
doSomething()
}
Lambdas 2
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
val result = ArrayList<R>()
for (item in this)
result.add(transform(item))
return result
}
//usage
val doubled = ints.map {it -> it * 2}
// also valid
val strings = computeStrings()
strings filter {it.length == 5} sortBy {it}
map {it.toUpperCase()}
Inline functions
// inline function
inline fun synchronized(lock: Lock, body: () -> Unit): Unit {
...
}
// the code ..
synchronized(lock) { foo() }
// .. will be transformed to
lock.lock()
try {
foo()
} finally {
lock.unlock()
}
Other
Cool features
- Ranges
- Type-safe builders
- Delegation
- Data classes
- Multi-declarations
- ...
How to use it?
- Maven, Gradle, Ant, and others supported
- Intellij IDEA plugin or standalone compiler
Size comparison*
Library | Jar Size | Method Count |
---|---|---|
kotlin-runtime-0.10.195 | 354 KB | 1071 |
kotlin-stdlib-0.10.195 | 541 KB | 5508 |
scala-library-2.11.5 | 5.3 MB | 50801 |
groovy-2.4.0-grooid | 4.5 MB | 29636 |
guava-18.0 | 2.2 MB | 14833 |
* From Jake Wharton's research (see links)
Links
- This presentation:
https://slides.com/antonrutkevich/kotlin-intro - Kotlin
http://kotlinlang.org/ - Jake Wharton's research
https://plus.google.com/+JakeWharton/posts/WSCoqkJ5MBj
anton.rutkevich@gmail.com
Contacts
Kotlin intro
By Anton Rutkevich
Kotlin intro
A brief intro to Kotlin language
- 1,132