swift and kotlin presentation
TRANSCRIPT
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
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
Simplified App Architecture
Model and Business Service Layers
Application Application
Activities
Fragments
ViewControllers Services
Model and Business Service Layers
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
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
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
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.
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)
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
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
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 ProGuardJava 55 KB 54 KB Kotlin 396 KB 57 KB
Original ProGuardJava 24 11 Kotlin 6,063 53
Similar Language Features
• Variables and Constants
• Functions and Methods
• Classes and Instantiation
• Classes and Inheritance
• Protocols and Traits
• Enums
Similar Language Features
• Nil and Null Safety (optional variables)
• Any and AnyObject
• Type Checks and Casts
• Generics
• Extensions and Typealias
• Error Handling
Swift Kotlinvar 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
Swift Kotlinclass 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
Swift Kotlinclass 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
Swift Kotlinclass 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
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
Swift Kotlinclass 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
Swift Kotlinenum 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
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.
Swift Kotlinvar 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
Swift Kotlinvar anything : Anyvar object : AnyObjectvar anything : Anyvar 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 : Anyvar listOfObjects: ArrayList<Any>
Any and AnyObject
Swift Kotlinlet 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
Swift Kotlinfunc genericFunction<T>(item: T) -> T { }
Note: AnyObject V Generics
• Strongly Typed • Flexible
fun genericFunction<T>(item: T): T { }
Generics
Swift Kotlinextension String { func toString() -> String { return "summary" }}
extension Array { mutating func add(item:T) { append(item) }}
typealias Integer = Inttypealias HashMap = NSMutableDictionarytypealias ArrayList = NSMutableArray
fun String.description(): String { return "summary"}
Extensions and Typealias
Swiftenum 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
Ignored Language FeaturesFeature Swift Kotlin
Class Import NO YESPackages NO OPTIONALExceptions NO YES
Visibility Modifiers YES YESPrimary Constructors NO YES
Annotations NO YESTuples YES NO
Property Observers YES NOOperator Overloading YES YES
Data Classes NO YESType Safe Builders NO YESReturns and Jumps NO YES
Language Cheatsheet
Swift Kotlin
nil null
self this
protocol trait
init constructor
func fun
-> :
let val
AnyObject Any
! !!
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
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