Share
Embed
Transcript
45 slides
-
// Kotlin val max = if (a > b) a
else b // Java int max = a > b ? a : b; -
val max = if (a > b) { print("Max is
a") a } else { print("Max is b") b } * else case is required when used as expression -
// Java switch (x) { case 1: System.out.println("x == 1");
break; case 2: System.out.println("x == 2"); break; default: System.out.println("x is neither 1 nor 2"); } // Kotlin when (x) { 1 -> println("x == 1") 2 -> println("x == 2") else -> println("x is neither 1 nor 2") } -
// Java switch (x) { case 1: case 2: System.out.println("x
== 1 or x == 2”); break; default: System.out.println("x is neither 1 nor 2"); } // Kotlin when (x) { 1..2 -> println("x == 1 or x == 2") else -> println("x is neither 1 nor 2") } -
when (obj) { 1 -> println("One") "Hello" -> println("Greeting") is
Long -> println("Long") !is String -> println("Not a string") else -> println("Unknown") } -
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.home ->
// Open the drawer. R.id.search -> // Show search. R.id.settings -> // Go to settings. else -> super.onOptionsItemSelected(item) } -
val charlie: Person? = null if (charlie != null) {
// use the object } charlie?.let { // let reads only once } -
// Kotlin when (x) { is Int -> print(x *
100) is String -> print("$x is a string") is Computer -> x.shutdown() } // Java if (x instanceof Integer) { System.out.println(((Integer)x) * 100); } else if (x instanceof String) { System.out.println(x + " is a string"); } else if (x instanceof Computer) { ((Computer) x).shutdown(); } -
Data classes •equals() / hashCode() •toString() •componentN() functions for destructuring
declarations •copy() data class Person(val name: String, val age: Int) -
Data classes Copying val bob = Person(“bob", 1) val olderBob
= bob.copy(age = 2) -
Data classes Destructuring Declarations val bob = Person("bob", 1) val
(name, age) = bob -
fun drawHRLine(character: Char = '=', length: Int = 10) {
for (i in 1..length) { print(character) } } drawHRLine('*') drawHRLine() drawHRLine(12) // Compile Error! Cannot do this drawHRLine('=', 12) // Does not seem real nice drawHRLine(length = 12) // Named argument -
// Java public String foo(String name, int number, boolean toUpperCase)
{ return (toUpperCase ? name.toUpperCase() : name) + number; } public String foo(String name, int number) { return foo(name, number, false); } public String foo(String name, boolean toUpperCase) { return foo(name, 42, toUpperCase); } public String foo(String name) { return foo(name, 42); } // Kotlin fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String { return (if (toUpperCase) name.toUpperCase() else name) + number } -
// Java public class Singleton { private static Singleton instance
= null; private Singleton() { } private synchronized static void createInstance() { if (instance == null) { instance = new Singleton(); } } public static Singleton getInstance() { if (instance == null) createInstance(); return instance; } } -
data class Person( var name: String, var age: Int, var
mobile: String = "", var email: String = "" ) Person(name = "Alice", age = 20).apply { mobile = "999999" email = "[email protected]" } -
val sum: (Int, Int) -> Int = { x, y
-> x + y } val sum = { x: Int, y: Int -> x + y } val notEmpty: (TextView) -> Boolean = { it.text.isNotEmpty() } val notEmpty = { textView: TextView -> textView.text.isNotEmpty() } Lamda Expressions -
// Java (Anonymous Inner class) fab.setOnClickListener(new View.OnClickListener() { @Override public
void onClick(View view) { doSomething(); } }); // Kotlin fab.setOnClickListener { doSomething() } -
data class Person( val id: String, var name: String, var
age: Int ) val (id) = Person("jayesh26121993", "Jayesh", 24) id.getBirthDate() // Return 26121993 // Extension function. fun String.getBirthDate(): String { return substring(length - 8, length) } -
Extension functions • Are the new Util classes • Are
not member functions • Do not modify the original class in any way • Are resolved at compile time by static type information • Are compiled to static functions in Java -
fun <T, R> Iterable<T>.map(predicate: (T) -> R): List<R> { val
destination = ArrayList<R>() for (item in this) { destination.add(predicate(item)) } return destination } Higher Order Function val original = arrayListOf(2, 4, 6, 8) original.map { it + 2 } // 4, 6, 8, 10 -
fun AppCompatActivity.setupActionBar(@IdRes toolbarId: Int, action: ActionBar.() -> Unit) { setSupportActionBar(findViewById(toolbarId))
supportActionBar?.run { action() } } // Set up the toolbar. setupActionBar(R.id.toolbar) { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) setTitle(R.string.home_title) } -
private inline fun FragmentManager.transact( action: FragmentTransaction.() -> Unit) { beginTransaction().apply
{ action() }.commit() } fragmentManager.transact { replace(frameId, fragment) } fragmentManager.transact { add(fragment, tag) } -
val string = buildSpannedString { append("no styling text") bold {
append("bold") italic { append("bold and italic") } } inSpans(RelativeSizeSpan(2f), QuoteSpan()) { append("double sized quote text") } } Spanning with KTX extensions -
val intent = Intent(this, SomeOtherActivity::class.java) intent.putExtra("id", 5) startActivity(intent) // With
Anko startActivity<SomeOtherActivity>("id" to 5) Intents with Anko -
Features covered • Null safety • Data classes • Default
and named arguments • Smart casts • Lamdas and Higher-Order functions • Extensions -
Not covered • Ranges • Exception handling • Visibility Modifiers
• Nested/Sealed/Enum classes • Coroutines • Generics -
References • https://kotlinlang.org/docs/reference/ • https://try.kotlinlang.org/ • https://github.com/MindorksOpenSource/from-java-to-kotlin • https://android.jlelse.eu/switching-from-java-to-kotlin-5-exciting-features- for-android-developers-49ce712a546
• http://www.baeldung.com/kotlin-when • https://twitter.com/AndroidDev • https://www.programiz.com/kotlin-programming/default-named-arguments • https://www.youtube.com/watch?v=5IOPd35j-ys