Share
Embed
Kotlin for Java developers.
Hadi Tok
February 27, 2020
Transcript
122 slides
-
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming
language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA -
Why Kotlin? Concise Drastically reduce the amount of boilerplate code
Source: kotlinlang.org /License: Apache 2.0 -
Why Kotlin? Safe Avoid entire classes of errors such as
null pointer exceptions Source: kotlinlang.org /License: Apache 2.0 Source: kotlinlang.org /License: Apache 2.0 -
Why Kotlin? Interoperable Leverage existing libraries for the JVM, Android,
and the browser Source: kotlinlang.org /License: Apache 2.0 -
fun sum(a: Int, b: Int): Int { return a +
b } Source: kotlinlang.org /License: Apache 2.0 -
fun sum(a: Int, b: Int): Int { return a +
b } fun sum(a: Int, b: Int) = a + b Source: kotlinlang.org /License: Apache 2.0 -
class MyStringCollection { infix fun add(s: String) { /*...*/ }
fun build() { this add "abc" // Correct add("abc") // Correct //add "abc" Incorrect: the receiver must be specified } } Source: kotlinlang.org /License: Apache 2.0 -
fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1]
// 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp } Source: kotlinlang.org /License: Apache 2.0 -
class Request { void longRunningOperation(Callback callback) { String result =
"result ok"; //assume long running callback.getResult(result); } interface Callback { void getResult(String result); } } -
Request request =new Request(); request.longRunningOperation(new Callback() { @Override public void
getResult(String result) { System.out.println(result); } }); -
class Request{ fun longRunningOperation(callback:(String)->Unit){ val result = "result ok" //assume
long running callback(result) } } -
val sum: (Int, Int) -> Int = { x: Int,
y: Int -> x + y } Source: kotlinlang.org /License: Apache 2.0 -
val sum: (Int, Int) -> Int = { x: Int,
y: Int -> x + y } sum(3,4) Source: kotlinlang.org /License: Apache 2.0 -
val a: Int = 1 // immediate assignment val b
= 2 // `Int` type is inferred Source: kotlinlang.org /License: Apache 2.0 -
var x = 5 // `Int` type is inferred x
+= 1 Source: kotlinlang.org /License: Apache 2.0 -
var a: String = "abc" a = null // compilation
error Source: kotlinlang.org /License: Apache 2.0 -
var b: String? = "abc" b = null // ok
Source: kotlinlang.org /License: Apache 2.0 -
val l: Int = a.length val m = b.length //
error: variable 'b' can be null Source: kotlinlang.org /License: Apache 2.0 -
val c: String? = null val l = if (c
!= null) c.length else -1 Source: kotlinlang.org /License: Apache 2.0 -
val a = "Kotlin" val b: String? = null println(b?.length)
println(a?.length) // Unnecessary safe call Source: kotlinlang.org /License: Apache 2.0 -
val listWithNulls: List<String?> = listOf("Kotlin", null) for (item in listWithNulls)
{ item?.let { println(it) } //prints Kotlin and ignores null } Source: kotlinlang.org /License: Apache 2.0 -
val l = if (c != null) c.length else -1
Source: kotlinlang.org /License: Apache 2.0 -
val l = if (c != null) c.length else -1
val l = c?.length ?: -1 Source: kotlinlang.org /License: Apache 2.0 -
var b: String? = "abc" val l = b!!.length Source:
kotlinlang.org /License: Apache 2.0 -
var a = 1 // simple name in template: val
s1 = "a is $a" a = 2 // arbitrary expression in template: val s2 = "${s1.replace("is", "was")}, now is $a" Source: kotlinlang.org /License: Apache 2.0 -
val s = "Hello, world!\n" val text = """ for
(c in "foo") print(c) """ Source: kotlinlang.org /License: Apache 2.0 -
val s = "Hello\nworld!" val text = """ for (c
in "foo") print(c) """ val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin() Source: kotlinlang.org /License: Apache 2.0 -
if (obj is String) { // `obj` is automatically cast
to `String` in // this branch return obj.length } Source: kotlinlang.org /License: Apache 2.0 -
if (obj !is String) return null // `obj` is automatically
cast to `String` in // this branch return obj.length Source: kotlinlang.org /License: Apache 2.0 -
// `obj` is automatically cast to `String` on the //
right-hand side of `&&` if (obj is String && obj.length > 0) { return obj.length } Source: kotlinlang.org /License: Apache 2.0 -
val items = listOf("apple", "banana") for (item in items) {
println(item) } Source: kotlinlang.org /License: Apache 2.0 -
for (x in 1..5) { print(x) } for (x in
1..10 step 2) { print(x) } Source: kotlinlang.org /License: Apache 2.0 -
for (x in 1..5) { print(x) } for (x in
1..10 step 2) { print(x) } for (x in 9 downTo 0 step 3) { print(x) } Source: kotlinlang.org /License: Apache 2.0 -
val items = listOf("apple", "banana") var index = 0 while
(index < items.size) { println("item at $index is ${items[index]}") index++ } Source: kotlinlang.org /License: Apache 2.0 -
fun describe(obj: Any): String = when (obj) { 1 ->
"One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } Source: kotlinlang.org /License: Apache 2.0 -
val fruits = listOf("banana", "avocado") fruits .filter { it.startsWith("a") }
.sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } Source: kotlinlang.org /License: Apache 2.0 -
class Person { var firstName: String var lastName: String constructor(firstName:
String, lastName: String) { this.firstName = firstName this.lastName = lastName } } -
class Person(var firstName: String, var lastName: String){ var name =
"$firstName $lastName" } -
class Person(var firstName: String, var lastName: String) { var name:
String get() = "$firstName $lastName" } -
class Person(var firstName: String, var lastName: String) { var name:
String get() = "$firstName $lastName" set(value) { val array = value.split(" ") firstName = array[0] lastName = array[1] } } -
class Person{ private String firstName; private String lastName; public String
getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } -
class Person{ private String firstName; private String lastName; public String
getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } } -
class Person{ private String firstName; private String lastName; public String
getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; } } -
sealed class Result() data class Success(val value: String) : Result()
data class Failure(val e: Exception) : Result() -
when(expr) { is Success -> println(result.value) is Failure -> println(result.e.message)
// the else is not required because covered all the cases } -
object PersonPrinter { fun printPerson(person: Person) { print(person.toString()) } }
PersonPrinter.printPerson(Person("Hadi", "Tok")) -
inline class Address(val value: String) object AddressPrinter{ fun printAddress(address: Address){
print(address.value) } } -
val lazyValue: String by lazy { println("computed!") "Hello" } fun
main() { println(lazyValue) println(lazyValue) } Source: kotlinlang.org /License: Apache 2.0 -
fun printer(){ GlobalScope.launch { val result = longRunningOperation() println("result is
$result") } } suspend fun longRunningOperation(): String { delay(5000L) return "200" } Source: kotlinlang.org /License: Apache 2.0 -
What is new with Java? Java 9 • Private methods
in interfaces -
What is new with Java? Java 10 • var keyword
(type inference) -
What is new with Java? Java 11 • Local Variable
Syntax for Lambda Parameters -
interface LambdaInterface { abstract void doSomething(String x); } LambdaInterface lambdaInterface
= ((String x) -> System.out.println(x) ); -
interface LambdaInterface { abstract void doSomething(String x); } LambdaInterface lambdaInterface
= ((var x) -> System.out.println(x) ); -
String result = ""; int number = 0; switch (0)
{ case 1: case 2: case 3: result = "low"; break; case 4: result = "ok"; break; case 5: case 6: case 7: result = "high"; break; default: result ="unknown"; } System.out.println("result"); -
String result ="" switch (0) { case 1,2,3: result =
"low"; break; case 4: result = "ok"; break; case 5,6,7: result = "high"; break; default: result ="unknown"; } System.out.println(result); -
String result = switch (0) { case 1, 2, 3
-> "low"; case 4 -> "ok"; case 5, 6, 7 -> "high"; default -> "unknown"; }; System.out.println(result); -
What is new with Java? Java 15 and later •
Text Blocks -
String html = """ <html> <body> <p>Hello, world</p> </body> </html>
"""; Source: http://openjdk.java.net/jeps/368 -
String html = """ <html> <body> <p>Hello, world</p> </body> </html>
"""; Source: http://openjdk.java.net/jeps/368 -
String html = """ <html> <body> <p>Hello, world</p> </body> </html>
"""; Source: http://openjdk.java.net/jeps/368 -
What is new with Java? Java 15 and later •
Text Blocks • Pattern Matching for instanceof -
What is new with Java? Java 15 and later •
Text Blocks • Pattern Matching for instanceof • Records -
record Person(String firstName, String lastName) { } Person p =
new Person("Hadi", "Tok"); Source: http://openjdk.java.net/jeps/368 -
record Person(String firstName, String lastName) { } Person p =
new Person("Hadi", "Tok"); System.out.println(p.firstName() + " " + p.lastName()); Source: http://openjdk.java.net/jeps/368 -
Questions? Usefull Links • Kotlin web site: ◦ https://kotlinlang.org/ •
Try Kotlin ◦ https://play.kotlinlang.org/ • KotlinConf 2019: What's New in Java 19: The end of Kotlin? by Jake Wharton : ◦ https://www.youtube.com/watch?v=te3OU9fxC8U