Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting Started With Kotlin

Getting Started With Kotlin

Leonardo Pirro

January 31, 2018
Tweet

More Decks by Leonardo Pirro

Other Decks in Programming

Transcript

  1. What is? Statically typed programming language Runs on the JVM

    Developed by JetBrains, first commit back in 2010 Object-oriented + Functional 100% interoperable with Java
  2. Hello Java My Old Friend • Java is “old” •

    Inability to add methods to platform types (Util class EVERYWHERE) • Nullability problems (NullPointerException, you know it) • Mutability problems • VERY, VERY, VERY… VER(Y)BOSE. No, serious. Java is Verbose.
  3. Hello Java My Old Friend • Java is “old” •

    Inability to add methods to platform types (Util class EVERYWHERE) • Nullability problems (NullPointerException, you know it) • Mutability problems • VERY, VERY, VERY… VER(Y)BOSE. No, serious. Java is Verbose. • Android API Design • Inheritance • Nullability, again (@Nullable everywhere) • APIs
  4. Kotlin to the rescue Kotlin is modern, simple and efficient,

    developed for Android (and more modern tools) in mind BUT No official support from Google
  5. Basic Syntax - Functions fun showToast(message: String, duration: Int): Unit

    { Toast.makeText(this, message, duration).show() }
  6. Basic Syntax - Functions Default arguments // Java void printMessage(String

    message) { System.out.println(message); } void printMessage(String message, String prefix){ System.out.format("%s %s", message, prefix); } void printMessage(String message, String prefix,String suffix){ System.out.format("%s %s %s", message, prefix, suffix); } // Kotlin fun printMessage(message: String, prefix: String = "", suffix: String = "") { println("$prefix $prefix $suffix") } printMessage("Uno") printMessage("Uno", "Due", “Tre") printMessage(suffix = "Tre", message = "Uno", prefix = "Due")
  7. Variables // Java int a = 1; String b =

    "i'm the one who knocks"; // Kotlin val a: Int = 1 val b: String = "I'm the one who knocks"
  8. Variables // Java int a = 1; String b =

    "i'm the one who knocks"; // Kotlin val a: Int = 1 val b: String = "I'm the one who knocks"
  9. Variables // Java int a = 1; String b =

    "i'm the one who knocks"; // Kotlin val a = 1 // Inferred type Int val b = "I'm the one who knocks" // Inferred type String
  10. (Im)mutability // Immutable Read-only variable val x = 1 x

    = 2 // Compile-time error "val cannot be reassigned" // Mutable variable var y = 2 y = 2 // OK
  11. (Im)mutability // Immutable variable val x = 1 x =

    2 // Compile-time error "val cannot be reassigned" // Mutable variable var y = 2 y = 2 // OK // Mutable variable var // Immutable variable val
  12. Null Safety: Nullable types and Non-Null types Non-Null types var

    name: String = "Leonardo" name = null // Compile-time error
  13. Null Safety: Nullable types and Non-Null types Non-Null types var

    name: String? = "Leonardo" name = null // OK
  14. Null Safety: Nullable types and Non-Null types fun getLength(string: String?):

    Int? { if(string != null) { return string.length } return 0 }
  15. Null Safety: Nullable types and Non-Null types fun getLength(string: String?):

    Int? { return string!!.length!! } For Null Pointer Exception Fans
  16. Null Safety: Nullable types and Non-Null types // Java public

    ZipCode getZipCode(User user){ if(user != null){ if(user.getAddress() != null){ return user.getAddress().getZipCode(); } } return null; } // Kotlin fun getZipCode(user: User?): ZipCode? { return user?.address?.zipCode }
  17. Null Safety: Nullable types and Non-Null types // Java public

    ZipCode getZipCode(User user){ if(user != null){ if(user.getAddress() != null){ return user.getAddress().getZipCode(); } } return null; } // Kotlin fun getZipCode(user: User?) = user?.address?.zipcode
  18. Classes // Java public class MainActivity extends AppCompatActivity { @Override

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } // Kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
  19. Classes class News (val title: String, val text: String, val

    tags: List<String>){ init { // Init code can be place here :) } .. }
  20. Classes (Models) - Java public class User { String firstName;

    String lastName; String phone; Date dateOfBirth; String email; public User(String firstName, String lastName, String phone, Date dateOfBirth, String email) { this.firstName = firstName; this.lastName = lastName; this.phone = phone; this.dateOfBirth = dateOfBirth; this.email = email; } 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; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getDateOfBirth() { return dateOfBirth; }
  21. Classes - Kotlin (Data classes) data class User(var firstName: String?,

    var lastName: String?, var phone: String?, var dateOfBirth: Date?) Kotlin Data classes = equals() + hashCode() + toString() + copy() 1 line in Kotlin VS 83+ lines in Java
  22. Classes - One Model class to rule them all //

    Models.kt data class User(val name: String, val surname: String, val email: String) data class Address(val street: String, val zipCode: ZipCode) data class ZipCode(val prefix: String, val postfix: String)
  23. Properties class User { var firstName: String? = null //

    mutable variable (getter/setter) var lastName: String? = null // mutable variable (getter/setter) val age: Int? = null // immutable (getter only) fun test(){ val user = User() // no 'new' keyword user.firstName = "Ajeje" // setter is called user.lastName = "brazof" // setter is called print("The name is ${user.firstName}") // getter is called } }
  24. Properties var firstName: String? = "" get() = "bla bla

    bla" set(value) { field = value + "bla bla bla" }
  25. Properties class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?)

    { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.setText("My awesome text") // Java style } }
  26. Properties class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?)

    { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.setText("My awesome text") // Java style textView.text = "My awesome text" // Kotlin property access } }
  27. Kotlin Synthetic - Goodbye findViewById public class HomeActivity extends AppCompatActivity

    { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); TextView textView = findViewById(R.id.textView); textView.setText("I drink and I know things"); } }
  28. Kotlin Synthetic - Goodbye findViewById public class HomeActivity extends AppCompatActivity

    { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); TextView textView = findViewById(R.id.textView); textView.setText("I drink and I know things"); } } TextView textView = findViewById(R.id.textView);
  29. Kotlin Synthetic - Goodbye findViewById import kotlinx.android.synthetic.main.content_main.* class MainActivity :

    AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.text = "My awesome text" } }
  30. Kotlin Synthetic - Goodbye findViewById import kotlinx.android.synthetic.main.content_main.* class MainActivity :

    AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.text = "My awesome text" } } import kotlinx.android.synthetic.main.content_main.* No findViewById() needed!
  31. Extension Functions fun Toast.show(message: String, duration: Int = Toast.LENGTH_SHORT){ Toast.makeText(this,

    message, duration).show() } Toast.show("My message", Toast.LENGTH_LONG )
  32. Extension Functions fun Toast.show(message: String, duration: Int = Toast.LENGTH_SHORT){ Toast.makeText(this,

    message, duration).show() } Toast.show("My message") Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show(); VS
  33. High-Order Functions fun <T> List<T>.filter (predicate: (T) -> Boolean): List<T>{

    val filteredList = ArrayList<T>() for(item in this){ if(predicate(item)){ filteredList.add(item) } } return filteredList } val names = listOf("Leonardo", "Federico", "Marco", "Daniele") val l = names.filter { it == "Leonardo" }
  34. Extension Function Expressions db.beginTransaction(); try { db.delete("news", "news_id = ?",

    new String[] {"46"}); } finally { { db.endTransaction(); } }
  35. Extension Function Expressions db.beginTransaction(); try { db.delete("news", "news_id = ?",

    new String[] {"46"}); db.setTransactionSuccessful(); } finally { { db.endTransaction(); } }
  36. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: () -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("news", "news_id = ?", arrayOf("46")) }
  37. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: () -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("news", "news_id = ?", arrayOf("46")) }
  38. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("news", "news_id = ?", arrayOf("46")) }
  39. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("news", "news_id = ?", arrayOf("46")) }
  40. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("news", "news_id = ?", arrayOf("46")) }
  41. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  42. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  43. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  44. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){ beginTransaction() try{

    func(this) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  45. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  46. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete(“news", "news_id = ?", arrayOf("46")) }
  47. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){ beginTransaction() try{

    func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { delete(“news", "news_id = ?", arrayOf("46")) }
  48. Extension Function Expressions fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit){ val editor

    = edit() editor.func() editor.apply() } preferences.edit { putString("name", "Paolo") putString("surname", "Blabla") remove("name") }
  49. Kotlin • Easy to learn • Modern, fast, efficient •

    Incredible usefull with Android • 100% Interoperable with Java • Makes your code cleaner and elegant
  50. Always code as if the guy who ends up maintaining

    your code will be a violent psychopath who knows where you live. - John F. Woods
  51. Link utili • Kotlin community: https://kotlinlang.org/community • Official Slack: http://slack.kotlinlang.org

    • Android Developers Italy: https://androiddevsitaly.slack.com Slide: https://goo.gl/AXhmQX https://goo.gl/nYLxY7