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

Friendly Natives: Swift and Kotlin

Friendly Natives: Swift and Kotlin

Every few months an elixir is offered up to mobile developments teams offering the dream of writing high performant native apps using a single language or framework for iOS and Android. Most often the promised benefits are negated by the extra layer of complexity which is introduced and the results are often suboptimal. In this talk, we explore a different approach which takes advantage of the similarities between the Swift language on iOS and the Kotlin language on Android. We examine if a pragmatic approach of harmonisation of parts of the code base is a potential development option to ease the burden of development for two fundamentally different platforms.

Andrzej Sitek

April 14, 2015
Tweet

More Decks by Andrzej Sitek

Other Decks in Programming

Transcript

  1. Speakers • Paul Murphy • Background: Java Server Side, Native

    Android and iOS Development, Javascript • Developed Apps for: Vodafone, MTN, Discover Digital, Avoca Learning, NPN, TVTextbook • Andrzej Sitek • Background: Front-End JavaScript, Node.js, Mobile Web and Native Android Development • Developed Apps for: MTN, Discover Digital, vRide, Vanstar, Egopolis, Mobile Nokaut.pl
  2. Introduction • Brief discussion of App development and the motivation

    for Cross Platform Development • The common language features of Swift and Kotlin • Short code demonstration of Swift and Kotlin and a Short IDE demo of AppCode and Android Studio • Conclusions • Questions
  3. Simplified App Architecture Model and Business Service Layers Application Application

    Activities Fragments ViewControllers Services Model and Business Service Layers
  4. What is Swift? • "Objective-C without the C" • Relatively

    new compiled programming language for iOS and OS X. It was Introduced at Apple's 2014 WWDC • It works well with Cocoa Touch, Foundation Classes and integrates well with existing Objective-C code • Developed by Apple and is very well supported • Built with the LLVM compiler framework and uses Objective-C runtime
  5. Why Swift? • Employs modern programming concepts • Simplified syntax

    comparing to Objective-C • Friendly syntax to Java, Javascript and C# developers • By default no pointers and unsafe accessors • Retains key Objective-C concepts • Can run together with C, C++ and Objective-C in a single program
  6. What features does Swift bring? • It is a nice

    syntax which is easy to learn • Strongly typed • Functions are first-class objects • Header files are not required anymore • Error handling rather than exception handling • Full support of Unicode in Strings
  7. The drawbacks of Swift • Relatively new - not many

    apps are written 100% in Swift yet • The iOS APIs are written with legacy data types, e.g. NSArray, NSDictionary - there is poor compatibility between these and the in built Swift datatypes • Swift is a strongly typed language which requires strict control over the initialisation of variables and the use of nil. This is a small challenge to get used to for existing Objective-C, Javascript and Java developers. • Experienced Objective-C developers are reluctant to take Swift on board for major projects. • A knowledge of Objective-C is still necessary when dealing with existing iOS APIs and third party libraries.
  8. What is Kotlin? • “Statically typed programming language targeting the

    JVM and JavaScript” • 100% interoperable with Java • Made by JetBrains (folks behind IntelliJ IDEA and, by extension, Android Studio) • Named after an island near Saint Petersburg (the location of the development office behind the project) • Introduced in 2011 (well before Swift!!!) • Android support came in 2nd milestone release (M2)
  9. Why Kotlin? • Actively developed and maintained by JetBrains •

    Designed to be light by excluding all the domain- specific heft • It has some of the core features missing in Java • Easy to integrate with Eclipse, IntelliJ, Android Studio (official JetBrains Kotlin plugin is available) • Versatile, No performance impact, very small runtime • Similar syntax to Swift
  10. What features does Kotlin bring? • Named and optional arguments

    • Lambdas • Null and type safety • Data objects • Simple singletons (object notation) • Traits (interfaces with default implementation) • Extension functions
  11. The drawbacks of Kotlin • It will take time until

    best practices emerge for Kotlin in the Android world • Annotation processors are not supported (such as Butterknife) • For more effective size and method count you have to enable ProGuard:
 Original ProGuard Java 55 KB 54 KB Kotlin 396 KB 57 KB 
 Original ProGuard Java 24 11 Kotlin 6,063 53
  12. Similar Language Features • Variables and Constants • Functions and

    Methods • Classes and Instantiation • Classes and Inheritance • Protocols and Traits • Enums
  13. Similar Language Features • Nil and Null Safety (optional variables)

    • Any and AnyObject • Type Checks and Casts • Generics • Extensions and Typealias • Error Handling
  14. Swift Kotlin var name: String = "Paul Murphy"
 var address:

    String = "Cork"
 
 let MON: String = "Monday"
 let TUE: String = "Tuesday"
 let WED: String = "Wednesday"
 let THU: String = "Thursday"
 let FRI: String = "Friday" var name: String = "Andrzej Sitek"
 var address: String = "Cork"
 
 val MON: String = "Monday"
 val TUE: String = "Tuesday"
 val WED: String = "Wednesday"
 val THU: String = "Thursday"
 val FRI: String = "Friday" Variables and Constants
  15. Swift Kotlin class FastFood {
 
 func createBurger(item: String, id:

    Int) -> Burger {
 let ingredientFactory = KCIngredientFactory()
 var burger = BeefBurger(factory: ingredientFactory)
 return burger
 }
 
 func createPizza(item: String, _ id: Int) -> Burger {
 let ingredientFactory = KCIngredientFactory()
 var burger = BeefBurger(factory: ingredientFactory)
 return burger
 }
 
 fun createOrders() {
 var burger = createBurger("beef", id: 101)
 var pizza = createPizza("pepperoni", 101)
 }
 
 } class FastFood {
 
 fun createBurger(item: String, id: Int): Burger {
 val ingredientFactory = KCIngredientFactory()
 var burger = BeefBurger(factory = ingredientFactory)
 return burger
 }
 
 fun createPizza(item: String, id: Int): Burger {
 val ingredientFactory = KCIngredientFactory()
 var burger = BeefBurger(factory = ingredientFactory)
 return burger
 }
 
 fun createOrders() {
 var burger = createBurger("beef", id = 101)
 var pizza = createPizza("pepperoni", 101)
 }
 
 } Functions and Methods
  16. Swift Kotlin class Burger {
 
 var id: Int
 var

    name: String
 
 init(id: Int, name: String) {
 self.id = id
 self.name = name
 }
 
 } 
 var burger = Burger(id: 101, name:"KC Burger")
 class Burger {
 
 var id: Int
 var name: String
 
 constructor(id: Int, name: String) {
 this.id = id
 this.name = name
 }
 
 } 
 var burger = Burger(id=101, name="KC Burger") Classes and Instantiation
  17. Swift Kotlin class Burger {
 
 var id: Int
 var

    name: String
 
 init(id: Int, name: String) {
 self.id = id
 self.name = name
 }
 
 } class BeefBurger : Burger {
 override init(id: Int, name: String) {
 super.init(id: id, name: name)
 }
 } 
 var burger = BeefBurger(id: 101, name:"KC Burger") open class Burger {
 
 var id: Int
 var name: String
 
 constructor(id: Int, name: String) {
 this.id = id
 this.name = name
 }
 
 } class BeefBurger: Burger {
 constructor(id: Int, name: String): super(id, name) {
 
 }
 } 
 var burger = BeefBurger(id=101, name="KC Burger") Classes and Inheritance
  18. Swift Kotlin protocol IngredientFactory {
 
 func createBeef() -> Beef


    
 func createChicken() -> Chicken
 
 func createFish() -> Fish
 
 func createCheese() -> Cheese
 
 func createToppings() -> Array<Topping>
 
 func createSauces() -> Array<Sauce>
 
 } trait IngredientFactory {
 
 fun createBeef(): Beef
 
 fun createChicken(): Chicken
 
 fun createFish(): Fish
 
 fun createCheese(): Cheese
 
 fun createToppings(): ArrayList<Topping>
 
 fun createSauces(): ArrayList<Sauce>
 
 } Protocols and Traits
  19. Swift Kotlin class KCIngredientFactory: IngredientFactory {
 
 func createBeef() ->

    Beef {
 return CorkBeef()
 }
 
 func createChicken() -> Chicken {
 return ChickenBreast()
 }
 
 func createFish() -> Fish {
 return BatteredFish()
 }
 
 func createCheese() -> Cheese {
 return Cheese.MatureCheddar
 }
 
 func createToppings() -> Array<Topping> {
 var toppings = Array<Topping>()
 toppings.add(Topping.Onions)
 return toppings
 }
 
 func createSauces() -> Array<Sauce> {
 var sauces = Array<Sauce>()
 sauces.add(Sauce.Mayo)
 sauces.add(Sauce.Ketchup)
 return sauces
 }
 
 class KCIngredientFactory: IngredientFactory {
 
 override fun createBeef(): Beef {
 return CorkBeef()
 }
 
 override fun createChicken(): Chicken {
 return ChickenBreast()
 }
 
 override fun createFish(): Fish {
 return BatteredFish()
 }
 
 override fun createCheese(): Cheese {
 return Cheese.MatureCheddar
 }
 
 override fun createToppings(): ArrayList<Topping> {
 var toppings = ArrayList<Topping>()
 toppings.add(Topping.Onions)
 return toppings
 }
 
 fun createSauces(): Array<Sauce> {
 var sauces = ArrayList<Sauce>()
 sauces.add(Sauce.Mayo)
 sauces.add(Sauce.Ketchup)
 return sauces
 }
 
 Protocols and Traits
  20. Swift Kotlin enum Cheese {
 case MatureCheddar
 case MeltyCheese
 }


    
 enum Topping {
 case IcebergLettuce
 case Gherkins
 case Pickles
 case Onions
 }
 
 enum Sauce {
 case Mayo
 case Ketchup
 case Mustard
 } enum class Cheese {
 MatureCheddar
 MeltyCheese
 }
 
 enum class Topping {
 IcebergLettuce
 Gherkins
 Pickles
 Onions
 }
 
 enum class Sauce {
 Mayo
 Ketchup
 Mustard
 } Enums
  21. The Billion Dollar Mistake Tony Hoare I call it my

    billion-dollar mistake. It was the invention of the null reference in 1965…..But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
  22. Swift Kotlin var a: String = “abc” a = nil

    // compilation error var b: String? = “abc” b = nil // ok class KCBurgerStand: BurgerStand {
 let factory = KCIngredientFactory()
 func createBurger(item: String) -> Burger {
 var burger: Burger?
 if (item == "beef") {
 burger = BeefBurger(factory: factory)
 burger!.name = "KC Special Burger"
 } else if (item == "chicken") {
 burger = ChickenBurger(factory: factory)
 burger!.name = "KC Breast In A Bun"
 } else if (item == "fish") {
 burger = FishBurger(factory: factory)
 burger!.name = "KC Atlantis Fish Burger"
 }
 return burger!
 }
 } var a: String = “abc” a = null // compilation error var b: String? = “abc” b = null // ok class KCBurgerStand: BurgerStand {
 val factory = KCIngredientFactory()
 fun createBurger(item: String): Burger {
 var burger: Burger? = null
 if (item == "beef") {
 burger = BeefBurger(factory: factory)
 burger!!.name = "KC Special Burger"
 } else if (item == "chicken") {
 burger = ChickenBurger(factory: factory)
 burger!!.name = "KC Creole In A Bun"
 } else if (item == "fish") {
 burger = FishBurger(factory: factory)
 burger!!.name = "KC Atlantis Fish Burger"
 }
 return burger!!
 }
 } Nil and Null Safety
  23. Swift Kotlin var anything : Any
 
 var object :

    AnyObject
 var anything : Any
 
 var listOfObjects: List<AnyObject>
 var listOfAnything: List<Any> Important for interacting with existing Objective-C APIs Objective-C id maps to Swift AnyObject id -> AnyObject 
 
 var object : Any
 
 var listOfObjects: ArrayList<Any> Any and AnyObject
  24. Swift Kotlin let beefBurger = BeefBurger()
 let chickenBurger = ChickenBurger()


    let fishBurger = FishBurger()
 let burgers = [beefBurger, chickenBurger, fishBurger]
 
 for item in burgers {
 if item is BeefBurger {
 // downcast
 let burger = item as BeefBurger
 burger.prepare()
 }
 } Uses is keyword Uses as keyword Type Checks and Casts
  25. Swift Kotlin func genericFunction<T>(item: T) -> T {
 
 }

    Note: AnyObject V Generics • Strongly Typed • Flexible fun genericFunction<T>(item: T): T {
 
 } Generics
  26. Swift Kotlin extension String {
 func toString() -> String {


    return "summary"
 
 }
 }
 extension Array {
 mutating func add(item:T) {
 append(item)
 }
 } typealias Integer = Int
 typealias HashMap = NSMutableDictionary
 typealias ArrayList = NSMutableArray fun String.description(): String {
 return "summary"
 } Extensions and Typealias
  27. Swift enum ServerResponse {
 case Result(String, String)
 case Error(String)
 }


    
 let success = ServerResponse.Result("CheeseBurger", "Paul Murphy")
 let failure = ServerResponse.Error("Out of cheese.")
 
 switch success {
 case let .Result(item, customerName):
 let serverResponse = "Sunrise is at \(item) for \(customerName)."
 case let .Error(error):
 let serverResponse = "Failure... \(error)"
 } Error Handling
  28. Ignored Language Features Feature Swift Kotlin Class Import NO YES

    Packages NO OPTIONAL Exceptions NO YES Visibility Modifiers YES YES Primary Constructors NO YES Annotations NO YES Tuples YES NO Property Observers YES NO Operator Overloading YES YES Data Classes NO YES Type Safe Builders NO YES Returns and Jumps NO YES
  29. Language Cheatsheet Swift Kotlin nil null self this protocol trait

    init constructor func fun -> : let val AnyObject Any ! !!
  30. Summary • Cross Platform Tools add a layer of complexity

    and dependency on third parties that can be easily avoided • Native App development on iOS and Android has traditionally been different • Swift and Kotlin share enough similarities in language design and syntax to consider being used in parallel for model and business app layers • The use of a shared and similar IDE platform eases parallel development in both languages
  31. References • Swift: https://developer.apple.com/swift/ • Kotlin: http://kotlinlang.org • Kotlin web

    demos: http://kotlin-demo.jetbrains.com/ • Kotlin on Twitter: https://twitter.com/project_kotlin