Upload
trinhdieu
View
216
Download
0
Embed Size (px)
Citation preview
The case for KotlinBARRY FEIGENBAUM, PH.D.
03/27/2018
Copyright © Barry Feigenbaum. All rights Reserved
Bye Java!Hello Kotlin!
Presenter:Barry Feigenbaum, Ph. D.
•Sr. Principal SW Engineer at Dell Enterprise• Currently working on storage management solutions
•Greater than 30 years of SW development experience• Developer, Architect, Manager, Evangelist, etc.
•Working with Java since near day one (stated with 1.0.2)• Oracle Certified
•Also C/C++, C#, Python and several other languages
•Adjunct Professor at ACC; past at St. Edwards and UT
•Author of multiple technical books and articles
Topics•Brief Kotlin Background
•Why Kotlin: What others in the community are saying
•Kotlin Feature Introduction/Tour
•Deeper Kotlin by Example
•Summary/Conclusion
•Questions?
Note: most uncredited code samples included herein come from:https://compsciclub.ru/media/slides/csseminar_2011_autumn/2011_10_02_csseminar_2011_autumn.pdfThey are a bit out of date but still informative.
Today Java is King of the JRE ‐but there are heirs apparentJava usage is widespread but declining over time◦ Why: Language is too verbose and lacks important modern language features◦ Java 8 ** (lambdas, etc.) was a major step forward, but still not enough◦ JCP process cannot keep up with demand for new features◦ Some level of resistance to extending Java (if not a “perfect” enhancement)
Several JVM languages attempt to overcome these missing features◦ Scala, Groovy, Jython, JRuby, Clojure, Kotlin, etc.◦ JRE (not a particular language) is the primary compatibility point
Kotlin is a well thought out compromise/union among competitors Strongly endorsed (by Google)Good pedigree (JetBrains)Rapidly gaining in popularityInterests entry programmers/schools
Announcement of Kotlin Support at Google IO 2017** Java 9 and 10 help a bit more.
What is Kotlin•Kotlin is a statically typed programming language that runs on the Java virtual machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure.
•While the syntax is not compatible with Java, Kotlin is designed to interoperate with Java code and is reliant on Java code from the existing Java Class Library, such as the collections framework.
•Kotlin uses aggressive type inference to determine the type of values and expressions for which type has been left unstated. This reduces language verbosity relative to Java, which demands often entirely redundant type specifications.
•Kotlin is designed to be an industrial‐strength object‐oriented language, and a "better language" than Java, but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin.
•In addition to the classes and methods (called member functions in Kotlin) ofobject‐oriented programming, Kotlin also supports procedural programming with the use of functions.
https://en.wikipedia.org/wiki/Kotlin_(programming_language)
Kotlin BackgroundA relatively new (since 2011) language for Java Runtime Environment (JRE)◦ Combinesmany “best” features of predecessors: Java, C#, Groovy, Scala, Ruby, and several others◦ Adds significant programmer efficiency and runtime safety vs. Java◦ A language comparable to C# in flexibility and power◦ Fully interoperable with Java code (call/return; interchangeable data types)
Grew up in Android world ◦ Trends show it supplanting Java as the preferred Android language◦ Formally endorsed by Google (Android owner)◦ Usage is spreading beyond Android
Free and Open Source
https://kotlinlang.org/; https://www.jetbrains.com/; https://www.jetbrains.com/idea/?fromMenu;
Excellent Kotlin IDE Support Available•Critical to attract Developers
•IDEA has Kotlin built‐in
•Eclipse supported via plug‐in
What others say about KotlinSUMMARY: KOTLIN IS WELL RECEIVED
What others say about Kotlin ‐ HerokuIt’s rare when a highly structured language with fairly strict syntax sparks emotions of joy and delight. Kotlin, which is statically typed and compiled like other less friendly languages, delivers a developer experience that thousands of mobile and web programmers are falling in love with.
The first thing you’ll notice about Kotlin is how streamlined it is compared to Java.We need Kotlin as an alternative to Java just as we needed Java as an alternative to C 20 years ago. Kotlinhas learned from the JVM languages that preceded it and borrowed the best parts from those ecosystems. The result is a well rounded, powerful, and production‐ready platform for your apps.
https://blog.heroku.com/rise‐of‐kotlin
What others say about Kotlin ‐ SpringKotlin is a statically typed language, but thanks to its clever type inference, it allows you to write code as short and expressive as dynamic language with performances close to pure Java projects
Properties support
Relatively lightweight standard library compared to other languages
Easy to learn: a Java developer can quickly understand most of the language (this quick comparison to Java is worth to read)
Java interop is a first class concern and great
Built‐in immutability and null safety support
Code is easy to read, efficient to write; No semicolon required ;‐)
Allows one to extend existing libraries without having to inherit
from the class or use any type of design pattern such as Decorator
https://spring.io/blog/2016/02/15/developing‐spring‐boot‐applications‐with‐kotlin
What others say about Kotlin ‐ ExpediaWhat we like:◦ Seamless interoperation with Java allows us to slowly migrate to Kotlin without having to throw away all of our current, working code.
◦ Converting to Kotlin has been fairly painless, thanks to functionality built into the Kotlin plugin for IntelliJ that automatically converts Java code to Kotlin.
◦ The explicit handling of null in Kotlin has helped us to dramatically reduce the number of dreaded NullPointerExceptions encountered by our users in the wild.
◦ Extension functions have allowed us to add functionality to platform classes, allowing for a more natural coding style and eliminating the need to create utility classes.
◦ Kotlin makes it easy to write less boilerplate and more concise code, so we can spend more time working on real functionality and finding and understanding the functionality becomes easier…. The data class is an excellent example of this.
◦ The Kotlin functional programming style operators, especially for dealing with collections.
There are still a few places where Kotlin falls short of Java:◦ No support among static code analysis tools (e.g. Fortify, SonarQube, etc.) means we lose out on the types of automated feedback these tools provide.
https://techblog.expedia.com/2017/05/18/learnings‐from‐two‐years‐of‐kotlin/
Brief tour of KotlinBY NO MEANS COVERING ALL OF KOTLIN’S FEATURES
Hello World!package org.kotlin.byexample // 1
fun main(args: Array<String>) { // 2
println("Hello, World!") // 3
}
1. Kotlin code is defined in packages. Like with Java, if you don’t define one, the default package will be used2. The main entry point to a Kotlin application is a function called main3. printlnwrites to standard output; it is implicitly imported
http://kotlinbyexample.org/examples/helloWorld
Note Kotlin uses type after name (vs. type before name as C derived languages do, such as Java) style
Where is the class definition? In Kotlin its not needed for top level static functions.Wrapping class generated from source file name.
package org.baf.hello;public class HelloWorld {
public static final void main(String[] args) {System.out.println(
"Hello, World!");}
}
Java Form:
Kotlin is briefer
Kotlin Base Types (all are reference types)(act as Java primitive equivalents)Numeric Types
Other types
Char 16
Boolean
Array
String
https://kotlinlang.org/docs/reference/basic‐types.html
Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8
Types have more function than Java primitives or primitive wrappers
Long/raw (ex. Reg ex) strings:val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn.|(Benjamin Franklin)
""".trimMargin()
Special TypesDifferent syntax, similar meaning
Nullable, function and tuple typesare not in Java (Optional is weak replacement for nullable type)
Special Reference Types• Any?: Root type (similar to Java’s
Object) but works better with generics
• Nothing: like Java’s null but is a type
• Unit: useful to declare the equivalent of voidmethods;assumed if a function has no return type
Kotlin Reserved WordsKotlin Operators
Kotlin keywords List
as break class continue do else
false for fun if in interface
is null object package return super
this throw true try typealias typeof
val var when while
These keywords are called hard keywords; !xxx and xxx? for some reservedSeveral soft (context) keyword exist
https://kotlinlang.org/docs/reference/keyword‐reference.html; grammar.html
Reserved for futureSimilar to Java
Sameness: ===, !==
Kotlin Packages/ImportsPackages/Imports work much like in Java but enhanced.
package foo.bar
import foo.Bar // Bar accessible unqualified
import foo.* // all public in package foo accessible
import bar.Bar as bBar // bBar stands for bar.Bar
The import keyword is not restricted to importing classes; you can also use it to import other declarations:•top-level functions and properties•functions and properties declared in object declarations•enum constants
https://https://kotlinlang.org/docs/reference/packages.html
A number of packages are imported into every Kotlin file by default:kotlin.*kotlin.annotation.*kotlin.collections.*kotlin.comparisons.*kotlin.io.*kotlin.ranges.*kotlin.sequences.*kotlin.text.*java.lang.*kotlin.jvm.*/kotlin.js.*
Kotlin Type AliasesType aliases provide alternative (generally shorter) names for existing types.
typealias NodeSet = Set<Network.Node>
typealias FileTable<K> = MutableMap<K, MutableList<File>>
typealias MyHandler = (Int, String, Any) -> Unit
typealias Predicate<T> = (T) -> Boolean
class A { inner class Inner }
class B { inner class Inner }
typealias AInner = A.Inner
typealias BInner = B.Inner
https://kotlinlang.org/docs/reference/type‐aliases.html
Type aliases are like macros, they do not introduce new types. They are equivalent to the corresponding underlying types. For example, when you add typealiasPredicate<T> and use Predicate<Int> in your code, the Kotlincompiler always expand it to (Int) -> Boolean. Thus you can pass a variable of your type whenever a general function type is required and vice versa
Kotlin Variable/Field DeclarationsKotlin has powerful type inference. Kotlin does not enforce immutability but it is recommended. In essence, prefer val over var.
var a: String = "initial" // 1
val b: Int = 1 // 2
val const = 3 // 3
var e: Int // 1
println(e) // 2
1. Declare a mutable variable and initialize it2. Declare an immutable variable and initialize it3. Declare an immutable variable and initialize it. The
compiler infers the type (as Int).
1. Declare a mutable variable, but don’t initialize it.2. Produces compiler error: Variable ‘e’ must be initialized
http://kotlinbyexample.org/examples/variables
String Templatesval greeting = "Kotliner"
println("Hello $greeting") // 1
println("Hello ${greeting.toUpperCase()}") // 2
1. Strings in Kotlin can include references to variables that are interpolated2. Can include any expression enclosed in curly braces
Generally easier to use than String.format
http://kotlinbyexample.org/examples/stringTemplates
Kotlin Variable Null Safetyvar neverNull: String = "This can't be null" // 1
var nullable: String? = "You can use null here" // 2
nullable = null // 3
var inferredNonNull = "The compiler assumes non-null" // 4
1. Declare a non‐null String variable2. Declare a nullable String variable3. Set the nullable variable to null4. When inferring types, the compiler assumes non‐null for variables that are initialized with a value
http://kotlinbyexample.org/examples/nullSafety
Working with Nullsfun describeString(maybeString: String?): String { // 1
if (maybeString != null && maybeString.length > 0) { // 2
return "String of length ${maybeString.length}"
} else {
return "Empty or null string"
}
}
1. A function that takes in a nullable String and gives you a phrase describing it2. If the given String is not null and not empty, tell the caller about it’s length
http://kotlinbyexample.org/examples/nullSafety
Note “?” which says type is “nullable” (can be null)
Null test needed only because type is nullable; Remove ? and variable cannot be null –checked by compiler
If/Else as Expression; Expression Functionfun describeString(maybeString: String): String = if (maybeString.length > 0)
"String of length ${maybeString.length}"
else
"Empty string"
http://kotlinbyexample.org/examples/nullSafety
Note no null test needed
If/Else, When, Try/Catch are expressions in Kotlin
As Casts – “unsafe” casts; Is Testsval x: String = y as String // 1
val x: String? = y as String? // 2
val x: String? = y as? String // 3
if (something is List<*>) { // 4
something.forEach { println(it) } // “it” is typed Any?
}
1. Exception if cannot cast; type wrong or value is null2. Exception if cannot cast; type wrong 3. No exception will be thrown; if cannot cast result is null4. Cannot cast to specific generic type (due to type erasure) so use wild card
https://kotlinlang.org/docs/reference/typecasts.html
For Loopsfun main(args: Array<String>) {
val cakes = listOf("carrot", "cheese", "chocolate")
for (cake in cakes) { // 1
println("Yummy, it's a $cake cake!")
}
}
1. Loops through each item in the list; like Java enhanced for but without need to declare loop variable’s type
http://kotlinbyexample.org/examples/loops
Ranges: replacement for for with index, other usesfor (i in 0..3) { …
for (i in 2..8 step 2) { … // 2
for (c in 'a'..'d’) { … // 3
for (c in 'a'..'g' step 2) { … // 4
for (i in 3 downTo 0) { … // 5
val x = 2
if (x in 1..10) { … // 6
val y = 3
if (y !in 1..4) { … // 7
1.Create range starting from 0 up to 3 (inclusive) and iterate over it2.You can define increment step for consecutive elements3.Char ranges can be created as well4.Increment step for char ranges are also valid5.To create a range in reverse order use downTo() function6.Ranges are also useful in if statements7.Note: !in is opposite of in. Statement is equal to _false_
http://kotlinbyexample.org/examples/ranges
While/Do Loopsfun main(args: Array<String>) {
var cakesEaten = 0
var cakesBaked = 0
while (cakesEaten < 10) { // 1
eatACake()
cakesEaten ++
}
do { // 2
bakeACake()
cakesBaked++
} while (cakesBaked < cakesEaten)
}
While and do‐while constructs work similarly to most languages.1. Performs the block while the condition is false2. Performs the block first, and then loops while evaluating the while condition.
http://kotlinbyexample.org/examples/loops
Continue/Break like in Java
Kotlin Collectionsval numbers: MutableList<Int> = mutableListOf(1, 2, 3)
val readOnlyView: List<Int> = numbers // immutable
println(numbers) // prints "[1, 2, 3]"
numbers.add(4)
println(readOnlyView) // prints "[1, 2, 3, 4]"
readOnlyView.clear() // -> does not compile
val strings = hashSetOf("a", "b", "c", "c")
assert(strings.size == 3)
val items = listOf(1, 2, 3)
https://kotlinlang.org/docs/reference/collections.html
Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc).
Kotlin Collections (cont)val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
println(readWriteMap["foo"])
val snapshot: Map<String, Int> = HashMap(readWriteMap)
val items = listOf(1, 2, 3, 4)
items.first() == 1; items.last() == 4 // both true
items.filter { it % 2 == 0 } // returns [2, 4]
val rwList = mutableListOf(1, 2, 3)
rwList.requireNoNulls() // returns [1, 2, 3]
if (rwList.none { it > 6 }) println("No items above 6")
val item = rwList.firstOrNull()
https://kotlinlang.org/docs/reference/collections.html
There are various useful extension methods on collections that are worth being familiar with.
Note operator overloading of […]
Note map item pair literals using “to”
Kotlin Classesclass Customer // 1
class Contact(val id: Int, var email: String) // 2
fun main(args: Array<String>) {
val customer = Customer() // 3
val contact = Contact(1, "[email protected]") // 4
contact.email = "[email protected]" // 5
}1. Declare a class named Customer with parameter‐less constructor2. Declare a class and named Contact with primary constructor taking id and email; properties id and email created3. Create an instance of the class Customer4. Create an instance of the class Contact using the constructor with two arguments5. Access the property email
http://kotlinbyexample.org/examples/classes
Empty classNo fields or methods
Kotlin Data ClassesOne frequently creates classes whose main purpose is to hold data. In such a class, standard functionality and utility functions can be mechanically derived from the data.
data class User(var name: String = "", var age: Int = 0)
Following methods automatically written by compiler:
•equals()/hashCode() pair
•toString() of the form "User(name=John, age=42)"
•componentN() functions corresponding to the properties in their order of declaration
•copy() function
https://kotlinlang.org/docs/reference/data‐classes.html
Kotlin Inheritanceopen class Dog { // 1
open fun sayHello() { // 1
println("wow wow!")
}
class Yorkshire : Dog() { // 2
override fun sayHello() { // 3
println("wif wif!")
}
fun main(args: Array<String>) {
val dog: Dog = Yorkshire()
dog.sayHello()
1. Kotlin classes/methods are final by default. To override a class, it must be marked with the open modifier.
2. A class inherits by following the subclass name with : SuperclassName(). Cannot be extended.
3. Overriding methods or attributes requires the override modifier.
http://kotlinbyexample.org/examples/inheritance
Closing “}” omitted to save space
Kotlin Delegate ClassesThe Delegation pattern has proven to be a good alternative to implementation inheritance. Kotlin supports it natively without boilerplate code.
For example, a class Derived can inherit from an interface Base and delegate all of its public methods to a specified object:
interface Base { fun print() }
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main(args: Array<String>) { val b = BaseImpl(10) Derived(b).print() // prints 10
}
The by‐clause in the super type list for Derived indicates that b will be stored internally in objects of Derived and the compiler will generate all the methods of Base that forward to b.
https://kotlinlang.org/docs/reference/delegation.html
Sealed Classes (with known subclasses)sealed class Mammal(val name: String) // 1
class Cat(val catName: String) : Mammal(catName)class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
when (mammal) { //2
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" //3
is Cat -> return "Hello ${mammal.name}" //4
//51. A sealed class is defined with two subclasses which must be in the same file2. The sealed class is used as an argument for a when expression3. A smart cast is performed, casting Mammal to Human4. A smart cast is performed, casting Mammal to Cat5. The else clause is not necessary here because all subclasses of the sealed class are covered. This is contrary to ordinary super classes, where
an else would always be needed
http://kotlinbyexample.org/examples/classes
Closing “}” omitted to save space
Operator OverloadingCan add operator functions to any class ◦ Including base types like Int◦ Because everything is an object in Kotlin
Can add (as extension functions) new operator–like behavior for any class◦ Ex. BigInteger supports x + y (vs. x.plus(y)) – much more readable◦ Class must just support (built‐in or extension) operator functions matching Kotlin operator namesSee some samples
◦ Operators mapped tofunction calls;Optimized for base types
See https://kotlinlang.org/docs/reference/operator‐overloading.html
Note functional style
this is an integer
Note concise body
Operator Overloading (cont)Makes dealing with different data types more consistent
Compare strings with “==“, “>” (vs. equals(), compareTo())
Can index strings, collections, maps, etc. with […]
Can extend function calls (unlimited possibilities)
Can support append (String + not special case)
See https://kotlinlang.org/docs/reference/operator‐overloading.html
Iterators and Operator Overloadingclass Animal(val name: String)
class Zoo(val animals: List<Animal>) {
operator fun iterator(): Iterator<Animal> { // 1
return animals.iterator() // 2
}
}
fun main(args: Array<String>) {
val zoo = Zoo(listOf(Animal("zebra"), Animal("lion")))
for (animal in zoo) { // 3
println(“It's a ${animal.name}")
}
}
1. Providing an iterator implementation (marked with operatormodifier)2. Returns the iterator for the list, which meets the method requirements3. Loops through each animal in the zooThe iterator can be declared on the type or as an extension function.
http://kotlinbyexample.org/examples/loops
Destructuring Assignments and Tuplesval (x, y, z) = arrayOf(5, 10, 15) // 1
val map = mapOf("Alice" to 21, "Bob" to 25)
for ((name, age) in map) { // 2
println("$name is $age years old")
}
val (min, max) = findMinMax(listOf(100, 90, 50, 98, 76, 83)) // 3
1. Create a component on the left‐hand side to match the arity of the right hand2. it can be used to iterate through maps. name and age variables are mapped to key and value now3. You can destruct built‐in Pairs and Triples, even as return values from functions
http://kotlinbyexample.org/examples/destructuring
Note Java 9 has similar constructors but no “to”
Destructuring Assignments (cont)data class User(val username: String, val email: String) // 1
fun main(args: Array<String>) {
val user = User("Mary", "[email protected]")
val (username, email) = user // 2
println(username == user.component1()) // 3
val (_, email) = user // 4
}
1. Define an immutable data class that will be destructured later2. Values mapped to object fields3. Data class automatically defines the component1(), component2() corresponding methods, called during destructuring; equals() used4. Use underscore if you don’t need one of the values, avoiding the compiler hint indicating unused variable
http://kotlinbyexample.org/examples/destructuring
Kotlin Function Definitionsfun printMessage(message: String): Unit { // 1
println(message)
fun printMessageWithPrefix(message: String, prefix : String = "") { // 2
println("[$prefix] $message")
fun sum(x: Int, y: Int): Int { // 3
return x + y
fun multiply(x: Int, y: Int) = x * y // 4
1. Create a function that takes a parameter of type string and returns Unit (i.e. no return value).2. Create a function that takes a second optional parameter with default value empty String. Also return Unit, which can be omitted.3. Create a function that returns an integer.4. Create a single‐expression function that returns an integer (inferred)
http://kotlinbyexample.org/examples/classes
Closing “}” omitted to save space
Concise form if only 1 expression;Int implied return type
Optional
Not optional
Kotlin Function Callsfun main(args: Array<String>) {
printMessage("Hello") // 1
printMessageWithPrefix("Hello", "Log") // 2
printMessageWithPrefix("Hello") // 3
printMessageWithPrefix(prefix = "Log", message = "Hello") // 4
val sum1 = sum(1, 2)
}
1. Call a function passing as argument Hello.2. Call a function with two parameters, passing a value for the second optional parameter.3. Call a function with two parameters, ignoring the second one.4. Call a function using named parameters and changing order of arguments.
http://kotlinbyexample.org/examples/classes
Extension Functions and Propertiesdata class Item(val name: String, val price: Float) // 1
data class Order(val items: Collection<Item>) // 2
fun Order.maxPricedItemValue(): Float =
this.items.maxBy { it.price }?.price ?: 0F // 3
fun Order.maxPricedItemName() = this.items.maxBy { it.price }?.name ?: "NO_PRODUCTS" // 4
val Order.commaDelimitedItemNames: String
get() = items.map { it.name }.joinToString()
1.We define simple models of Item and Order. Order can contain arbitrary Collection of Item s2.We define extension functions for Order type. Later we call these functions directly on the instance of that type.3.We can also define extension properties.4.Read more about signature of https://kotlinlang.org/docs/reference/extensions.html[extensions].
http://kotlinbyexample.org/examples/extensionFunctions
data classes get properties defined from constructor and auto generation of toString, equals, hashCode
Lambda call; no (…)
Extension Functions on null valuesfun <T> T?.nullSafeToString() = this?.toString() ?: "NULL" // 1
1.It is even possible to execute extensions on null references. In their implementation we can check for null reference and based on that we can do any arbitrary logic.
http://kotlinbyexample.org/examples/extensionFunctions
Coroutines: Generators (for indefinite sequences)val fibonacciSeq = buildSequence {
var a = 0
var b = 1
yield(1)
while (true) {
yield(a + b)
val tmp = a + b
a = b
b = tmp
}
}
http://www.baeldung.com/kotlin‐coroutines
public abstract suspend fun yield(value: T)
val res = fibonacciSeq.take(5).toList()assertEquals(res, listOf(1, 1, 2, 3, 5))
Coroutines: asynch executionrunBlocking<Unit> {
val one = async(CommonPool) { someExpensiveComputation(1000L)
}val two = async(CommonPool) {
someExpensiveComputation(5000L) }runBlocking {
one.await()two.await()
}}
http://www.baeldung.com/kotlin‐coroutines
Leverage the async() coroutine to achieve concurrency.After we submit the two expensive computations, we suspend the coroutineby executing the runBlocking() call. Once results of one and two are available, the coroutine will resume, and the results are returned. Similar to threads but more lightweight.
Calling Java from Kotlinimport java.util.*
fun demo(source: List<Int>) {
val target = ArrayList<Int>()
// 'for'-loops work for Java collections:
for (item in source) {
target.add(item)
}
// Operator conventions work as well:
for (i in 0..source.size - 1) {
target[i] = source[i] // get and set are called
}
}
http://kotlinbyexample.org/examples/letFunction
Kotlin is designed with Java Interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well.
Note operator overload of […] operator applied to Java collections as well as Kotlincollections via Extension Functions;No need to call get/set methods
Accessing Java “properties” from Kotlinimport java.util.Calendar
fun calendarDemo() {
val calendar = Calendar.getInstance()
if (calendar.firstDayOfWeek == Calendar.SUNDAY) {
calendar.firstDayOfWeek = Calendar.MONDAY}
}
if (!calendar.isLenient) {
calendar.isLenient = true
}
}
http://kotlinbyexample.org/examples/letFunction
Methods that follow the Java conventions for getters and setters are represented as properties in Kotlin.
Calls Java “get” access method
Calls Java “set” access method
A deeper look:Kotlin by ExampleKOTLIN IS ARGUABLY A BETTER JAVA THAN JAVA
TOO MANY ENHANCEMENTS TO COVER COMPLETELY; JUST A SAMPLE HERE
Hello World, AgainSimilar to Java◦ Some syntax differences (names, declarations, minor statement structure)◦ Types come after (vs. before) the name
Standalone functions are available◦ More like c/C++◦ main() does not need to be inside a class
◦ Note null safe call ofprintln
Direct calls to Java
Note: no semicolons at line ends
Hello World,again
Extensions ◦ Everythingis an object
◦ Operator overloading
◦ TemplateStrings
◦ Extensionfunction on standard JRE type
Plain Old Java TypeDon’t use new;just constructor
AgainExtensionmethods
Exploitsfunctionalstyle
Lots of JRE inte‐grationandextension
this is an Iterable
A function literal (AKA a Lambda)
Null Safety?. prevents invoking times()if x is null
val: finalvar: can change
Note x, y type is inferred
null * ? undefined
Ok, x never null here
Int: may not be null; compiler verifiesInt?: may be null
Automatic CastsIf/WhenCase matching goes way beyond Java’s switch simple equality
Once matched, value is automatically/implicitly cast to correct type
(vs. ((String)obj).substring(2))
Works for if/when
Enhanced Switch
https://blog.philipphauer.de/blog/2018/0315‐talk‐javaland‐2018/slides‐kotlin‐in‐practice‐javaland‐2018.pdf
Some examples show old syntax
Classes and InheritanceClasses are similar to in Java but with some different syntax
Visibility, final defaults different (default what is needed more often)
Can define constructor in class signature
If data class, can define all properties (auto generate field and accessmethods)
Class “objects”Replaces Java static fields/methods
More like a singleton associated with a class
FunctionsMay be inside/outside of classes
Non‐member functions are similar to Java staticmethods
There is a formal functiontype (closest in Java is @FunctionalInterface)but no interface needed
Nested functions allowed;
Helpful for small scope functions
(AKA Lambdas)
(no names)
Higher Order FunctionsFunctions that return functions or take functions as arguments
Similar to using Java Lambdas
Kotlin does not distinguish checked exceptions; no need to declare them on functions
In Kotlin, functions have full (R/W) closures (vs. Java’s RO lambda closures)
Function ApplicationFunctions can be in‐lined (strong optimization)
Can do similarthings as Java Lambdas
Function Call Sugar
Infix (vs. dot) format◦ Very nice to make DSLs◦ No (…) needed if 1 argument
LINQ–like syntax◦ Similar to Java streamsbut with cleaner syntax
◦ Function passed adjacent (vs.as parameters)
LINQ (Language Integrated Query): .NET way to process collections (ex. SQL SELECT results)
Extension Functions(static) Functions effectively added to an existing class
Useful to access functions with the target class and not in distinct utility classes
Declares as Xxx.fff()fff() becomes a part of Xxx
Called with dot (vs.function call) syntax◦ x.fff() vs.◦ fff(x)
Not in Java
More Complete ExamplesCLOSER TO THE REAL WORLD
Example: Linear SearchFor basic algorithmsKotlin is very similar to Javathus Kotlin is easy to learn
Kotlin offershelpful extensions:◦ public by default◦ final by default◦ Tupleswith destructing assignment
◦ Extension function
https://github.com/bmaslakov/kotlin‐algorithm‐club/blob/master/src/main/io/uuddlrlrba/ktalgs/search/LinearSearch.kt
Example:Binary Tree
Simple Binary Tree implementation
Note how easy it is to create a tree literally (basically a tree DSL)
Note class fields and constructors implied by class declaration; values
Body can beempty
Immutable singletonobject (a lot like Java enum instances are)
https://github.com/dkandalov/kotlin‐99#logic‐and‐codes
We will use the following classes to represent binary trees (see Tree.kt). An End is equivalent to an empty tree. A Node has a value, and two descendant trees. The toString() functions are relatively arbitrary and were written to produce minimal readable output. Note the usage of variance annotation out T which makes classes covariant; it will be able to hold subtypes of whatever type it's created for. End is declared as value because data classes must have at least one constructor parameter. End has type parameter of Nothing which is a subtype of every other type.
Builders/internal DSLsCreate a DSL to author other languages
Ex. Generate HTMLusing Kotlin code
Allows code to bemixed with text(like JSP but cleaner)
Not in Java
Powerfully addition for creating complex data or text
DSL – Doman Specific Language
HTML tags are function calls taking lambdas
“+” here is overloaded operator unary plus
https://github.com/gyulavoros/kotlin‐todomvc/blob/master/backend/src/main/kotlin/co/makery/todomvc/backend/css.kt
Builder ExampleLibrary provides element definitions
Build CSS stylesheet directly in Kotlin◦ Note use of Kotlin expression in CSS(Integer extension function percentcalled wo using (); more readable)
https://github.com/gyulavoros/kotlin‐todomvc/blob/master/backend/src/main/kotlin/co/makery/todomvc/backend/css.kt
Note percentmethod added to Int
Builder Example (cont)Library provides element definitions
Build HTML server directly in Kotlin
Responds to path “/”
https://https://github.com/gyulavoros/kotlin‐todomvc/blob/master/backend/src/main/kotlin/co/makery/todomvc/backend/main.kt
Ktor is a framework for building servers and clients in connected systems using powerful Kotlin programming language. This website provides a complete reference to the Ktor application structure, programming interface and how to approach particular tasks.
https://dzone.com/articles/using‐kotlin‐with‐ktor‐to‐create‐web‐apps
Builder for SQL•Build SQL programmatically and with type safely
•Example SQL statement literal (lots of room for error; typos, etc.):SELECT Country.name, COUNT(Customer.id)FROM Country JOIN Customer ON Country.id = Customer.country_idGROUP BY Country.name ORDER BY COUNT(Customer.id) DESC LIMIT 1
•Equivalent SQL (as code) via Kotlin builder syntax:(Country innerJoin Customer).slice(Country.name, Count(Customer.id)).selectAll().groupBy(Country.name).orderBy(Count(Custmer.id), isAsc=false).limit(1)
https://github.com/JetBrains/Exposed
Concise Database (JDBC) access
https://github.com/JetBrains/Exposed
Can easily create table access objects
Can express SQL as code (type safe and parsed early)
Note use of SQL terminology
Sample Database Client
Client is simple and expressive
Similar to JPA API
Partial code
https://github.com/JetBrains/Exposed
Spring Boot and KotlinKotlin significantly reduces the code (and boilerplate) needed to create a REST service
Kotlin code is safer (NPE reduced naturally)
Kotlin fully interoperateswith JRE and Spring
Annotations/types are pure Spring/JPA
Note: add data before class and get all properties get/set, equals, hashCode and toStringfor free
https://resources.jetbrains.com/storage/products/kotlinconf2017/slides/Why+Spring+loves+Kotlin.pdf
Spring Boot and Kotlin (cont)Defining the Spring Boot application is easy in Kotlin.
Long strings w/templates:
https://resources.jetbrains.com/storage/products/kotlinconf2017/slides/Why+Spring+loves+Kotlin.pdf
Spring Boot and Kotlin (cont)Data classes can really help
“cute” names can be helpful Even more
https://resources.jetbrains.com/storage/products/kotlinconf2017/slides/Why+Spring+loves+Kotlin.pdf
Guess What! Kotlin can do front–enddevelopment tooSimilar to Node.js running in client andserver
Note access to DOM
Partial listing
• Kotlincompiled to JavaScript
• Runs in a browser
Summary
Kotlin has an improving EcosystemBooks: https://kotlinlang.org/docs/books.html◦ More coming over time
Key frameworks supporting Kotlin; Examples:◦ Spring: https://spring.io/blog/2016/02/15/developing‐spring‐boot‐applications‐with‐kotlin
◦ Vert.x: http://vertx.io/blog/vert‐x‐3‐4‐0‐beta1‐release/
https://kotlinconf.com/talks/
Not including android‐oriented books
Local Kotlin User Groups are a place to share experience between Kotlin programmers and to get newcomers excited about the language. > 100 users groups (and growing)
Kotlin Nights are one‐off events that usually include 3‐4 talks on Kotlin.
There are over2000 repositories on GitHubalone with Kotlin projects. ◦ These are just a few of them: http://kotlinlang.org/docs/resources.html.
https://blog.kotlin‐academy.com/
stack overflow and others
Kotlin has agrowing Community
Several Java “flaws” mitigated/addressed in Kotlin
•Null references are controlled by the type system
•No raw types
•Arrays in Kotlin are invariant
•Kotlin has proper function types, as opposed to Java’s Single Abstract Method (SAM) interface conversions
•Use‐site variance without wildcards
•Kotlin does not declare/treat as special checked exceptions and thus does not deal the complexity they create
https://kotlinlang.org/docs/reference/comparison‐to‐java.html
Java has but Kotlin does not –Not always a plus for Java•Checked exceptions•Primitive types that are not classes•Static members (use object type instead)•Non‐private fields•Wildcard‐types for Generics•Ternary‐operator a ? b : c (use if/else expression instead)
https://kotlinlang.org/docs/reference/comparison‐to‐java.html
Kotlin has but Java does notGenerally an improvement over Java•Lambda expressions + Inline functions means performant custom control structures
•Extension functions•Null‐safety•Smart casts•String templates•Properties•Primary constructors•First‐class delegation•Type inference for variable** and property types•Singletons
•Declaration‐site variance & Type projections•Range expressions•Operator overloading•Companion objects•Data classes•Separate interfaces for read‐only and mutable collections•Coroutines (acts like lightweight threads)
https://kotlinlang.org/docs/reference/comparison‐to‐java.html**: added in Java 10 for local variables
Kotlin vs. Java (from NetFlix)Look at Java Look at Kotlin
https://resources.jetbrains.com/storage/products/kotlinconf2017/slides/NetflixKotlin.pdf
Kotlin Pros/ConsPros
Increased productivity
Less error‐prone than Java
Reuse of the powerful and well‐known Java ecosystem
Interoperability with Java.
Easy to learn. No paradigm shift.
Stepwise migration possible. You can use Kotlin and Java at the same time within a project.
Increased attractiveness for applicants. Modern languages attract skilled developers.
Brilliant IDE support with IntelliJ IDEA.
Cons
Further development of the language depends on JetBrains.
Support for other IDEs (like Eclipse) is not as mature as IntelliJ.
Less documentation available compared with Java.
ConclusionAll in all, we claim that introducing Kotlin comes with low risks. Kotlin is easy to learn, you stay in the familiar Java ecosystem and you can start using Kotlinalongside with Java.
https://blog.philipphauer.de/kotlin‐java‐ecosystem‐language/
https://blog.philipphauer.de/blog/2018/0315‐talk‐javaland‐2018/slides‐kotlin‐in‐practice‐javaland‐2018.pdf
Summary of Excerpts (multiple sources)•… is how streamlined it (Kotlin) is compared to Java
•Kotlin is a statically typed language yet it allows you to write code as short and expressive as dynamic language
•Java interop is a first class concern and great•Built‐in immutability and null safety support
•Code is easy to read, efficient to write; more robust and readable code
•Spring and Kotlin play well together•I don’t want to write Java anymore
•Kotlin has a bright future•Can slowly migrate to Kotlin without throw away of working code
To me, the language is easy to get started with coming from C#. In fact, it feels like it combined the best things from C# with some F#, Swing, TypeScript, etc. — in short: It’s enjoyable! ‐ https://dzone.com/articles/running‐kotlin‐in‐azure‐functions
Why Kotlin (from )•Full Java interoperability
•Compiles as fast as Java
•Safer than Java (harder to code many Java coding flaws)
•More concise than Java (significant coding time saver)
•Way simpler than Scala**
** Considered the most safe (popular) OOP+Functional combo language for JRE; hard to master
• Java was created because C++ was considered too complex
• Kotlin was created because Scala was considered too complex
Conclusion – Kotlin is likely the next JavaPros:
Kotlin offers significant programmer productivity over Java
Kotlin offers significantly improved code safety/quality over Java
Kotlin is fully interoperable with Java code; can mix and match
Kotlin is mainstream on Android and is not going away (at version 1.2 and continuing)
Cons
Kotlin is not Java; it does not (yet) have the base Java has
Kotlin has a (smallish; especially for Java programmers) learning curve
Kotlin is weak on 3rd party tools (vs. Java)
Kotlin is not a 100% superset of Java◦ Thus all Java code cannot be rewritten in Kotlin
Java Kotlin
Questions?