Share
Embed
Kotlin lang
Droidup 2.0 Tbilisi; Language design, futures and base syntax overview
Jemo Mgebrishvili
November 20, 2016
Transcript
41 slides
-
{ Kotlin } Statically typed language for the JVM, Android
and the browser. Developed by JetBrains First stable release February 15, 2016. -
{ Syntax }. var and val var <propertyName>: <Type> =
[property initializer] get() // optional set() // optional //example var str: String = “kotlin is awesome" OR var str = “kotlin is awesome" -
{ Syntax }. method declaration fun <methodName> : <ReturnType> //example
fun saySomthing() : String { return “kotlin is awesome" } OR fun saySomthing() = “kotlin is awesome" -
{ Syntax } when (x) { in 1..10 -> print("x
is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } -
{ Syntax } for ((k, v) in map) { println("$k
-> $v") } someObject?.let { // execute this block if not null } fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } } -
{ Syntax } .inheritance all classes by default are finals
open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} } -
{ Syntax } .inheritance open class A { open fun
f() { print("A") } fun a() { print("a") } } interface B { fun f() { print("B") } fun b() { print("b") } } class C() : A(), B { // The compiler requires f() to be overridden: override fun f() { super<A>.f() // call to A.f() super<B>.f() // call to B.f() } } -
{ Syntax } .inner classes class A { // implicit
label @A inner class B { // implicit label @B fun foo() { val a = this@A // A's this val b = this@B // B's this } } } -
Billion-dollar mistake Tony Hoare My goal was to ensure that
all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. -
{ null safety } nullable and non-nullable types var str:
String = “kotlin is awesome" str = null // compilation error… str is non-nullable type var str: String? = “kotlin is awesome" str = null // ok... str now can be null val length = name.length // compilation error val length = name?.length // ok -
{ null safety } nullable and non-nullable types var name:
String? = “some string" if (name != null){ length = name.length }else{ length = 0 } or more shortly val length = name?.length ?: 0 -
{ Default parameters } fun tmpMethod(a: Int = -10, b:
Int = 5, c: Int = 0){ print(a + b + c) } ---------------------------------------------------------------- tmpMethod(1) // 7 tmpMethod(2) // -8 tmpMethod(1,2,3) // 6 tmpMethod(b = 0, a = 2) // 2 -
{ Delegated Properties } val lazyValue: String by lazy {
println("computed!") "Hello" } fun main(args: Array<String>) { println(lazyValue) println(lazyValue) } This example prints: computed! Hello Hello -
{ Delegated Properties } var age: Int by Delegates.observable(0) {
prop, old, new -> println("$old -> $new") } age = 10 // 0 -> 10 age = 11 // 10 -> 11 -
{ Extensions }.methods val nullableString : String? = null if
(nullableString.isNullOrEmpty()){ // nullableString is null or empty } -
{ Extensions }.methods var myObject : MyClass? = null if
(myObject.isNull()){ // my object is null } -
{ Extensions }.methods var myObject : MyClass? = null if
(myObject.isNull()){ // my object is null } fun MyClass?.isNull() : Boolean { return this == null } OR fun MyClass?.isNull() = this == null -
{ Extensions }.methods fun Activity.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT)
{ Toast.makeText(this, msg, toastLength).show() } fun Fragment.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, msg, toastLength).show() } -
{ Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex =
myList.lastIndex // lastIndex = 4 -------------------------------- -
{ Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex =
myList.lastIndex // lastIndex = 4 -------------------------------- val <T> List<T>.lastIndex: Int get() = size - 1 -
{ Lambdas } Collections.sort(items, { t1, t2 -> t1.name.compareTo(t2.name)}) ---------------------------------------------------------------------------------------------------------
in java Collections.sort(items, new Comparator<MyClass>() { @Override public int compare(MyClass t1, MyClass t2) { return t1.getName().compareTo(t2.getName()); } }); -
{ Higher-Order funcitons} fun <T, R> List<T>.map(transform: (T) -> R):
List<R> { val result = arrayListOf<R>() for (item in this) result.add(transform(item)) return result } val doubled = items.map { it * 2 } fun <T> max(collection: Collection<T>, less: (T, T) -> Boolean): T? { var max: T? = null for (it in collection) if (max == null || less(max, it)) max = it return max } val less = {a:Int,b:Int -> a > b} -
Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try {
db.delete("tableName","firstName =?", arrayOf("Jake")) db.setTransactionSuccessful() }finally { db.endTransaction() } -
Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try {
// do work here db.setTransactionSuccessful() }finally { db.endTransaction() } -
{ Extension Function Expression } fun SQLiteDatabase.inTransaction(func: () -> Unit)
{ beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { db.delete("tableName","firstName =?", arrayOf("Jake")) } -
{ Extension Function Expression } fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit)
{ beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { delete("tableName","firstName =?", arrayOf("Jake")) } -
{ Kotlin in Android } // in java Button button
= (Button) findViewById(R.id.my_button_id); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin val button = findViewById(R.id.my_button_id) as Button button.setOnClickListener { toast("clicked") } -
{ Kotlin in Android } // JAVA button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override public void onGlobalLayout() { button.getViewTreeObserver().removeOnGlobalLayoutListener(this); Toast.makeText(Main2Activity.this, button.getHeight() +"", Toast.LENGTH_SHORT).show(); } }); kotlin any_type_view.afterMeasured { toast(any_type_view.height.toString()) } -
{ Extension Function Expression } inline fun View.afterMeasured(crossinline f: View.()
-> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) } -
{ Kotlin in Android } // in java button.setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin button.setOnClickListener { toast("clicked") } -
{ Kotlin in Android }. no more findViewById Syntetic import
apply plugin: 'kotlin-android-extensions' my_button_id.setOnClickListener { } my_text_view_id.text = "some text" <Button android:id="@+id/my_button_id" android:layout_width="match_parent" android:layout_height="50dp" /> <TextView android:id="@+id/my_text_view_id" android:layout_width="match_parent" android:layout_height="wrap_content" /> -
{ Kotlin in Android }.Anko library async() { // Do
something in a secondary thread uiThread { // Back to the main thread } } -
with kotlin you get • lambdas • default methods •
method references • extension lambdas • nullable types • null safety • inlined methods (which reduce the cost of lambdas immensely) • extension methods • improved type inference • operator overloading (limited) • infix methods • reified generics for methods • data classes • property delegation • interface delegation