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

Swift and Kotlin

Avatar for Manav Manav
November 24, 2016

Swift and Kotlin

If you write code in Objective C or Java, Swift and Kotlin will make you happy.

Avatar for Manav

Manav

November 24, 2016

Other Decks in Programming

Transcript

  1. func main(args: Array<String>) { print("Hello, " + args[0]) } fun

    main(args: Array<String>) { println("Hello, " + args[0]) }
  2. If you write code in Objective C or Java, Swift

    and Kotlin will make you happy.
  3. Immutablity is an easily expressible first class citizen of the

    type system. let packet = Packet("iq") var packet = Packet("iq") val packet = Packet("iq") var packet = Packet("iq")
  4. // String -> URL? let url: URL? = URL(string: myString)

    // URL -> URLRequest let request = URLRequest(url: url)
  5. Why is ?: called* the Elvis operator? Quiz * “Nil/Null

    Coalescing”, cause Elvis is too cool for official documentation
  6. guard let marriedGuy = person as? MarriedGuy else { return

    “Did you even read the docs?” } marriedGuy.wife.family?.meet()
  7. if (person !is MarriedGuy) { return “Did you even read

    the docs?” } person.wife.family?.meet()
  8. fun oh(missingPerson: Person?): String { if (missingPerson == null) {

    return “Nobody’s missing” } return missingPerson.name() + “ got lost” }
  9. when (x) { is Int -> print(x + 1) is

    String -> print(x.length + 1) is IntArray -> print(x.sum()) } * Example taken from Kotlin docs
  10. This is just boilerplate code obsuring the fact that we

    want to, yes really want to, oh here is another legacy annotation! return a buggy racecar from this function. This function returns a buggy racecar.
  11. The lesser code is not because of a less powerful

    language. In fact, the Swift and Kotlin compilers work with richer semantics when parsing your code. They just do the grunt work for you.
  12. new Thread(() -> { // do stuff }); Java 8

    / Android with Retrolambda
  13. @interface Person : NSObject @property (nonatomic, readonly) NSString *name; @property

    (nonatomic) NSInteger age; @end @implementation Person - (instancetype)initWithName:(NSString *)name age:(NSInteger)age { self = [super init]; if (self) { _name = name; _age = age; } return self; } @end
  14. @implementation Person - (BOOL)isEqualToPerson:(Person *)person { return [self.name isEqual:person.name] &&

    self.age == person.age; } - (BOOL)isEqual:(id)object { if (self == object) { return YES; } if (![object isKindOfClass:[Person class]]) { return NO; } return [self isEqualToPerson:(Person *)object]; } - (NSUInteger)hash { return [self.name hash] ^ (unsigned long)self.age; } @end
  15. class Person { private final String name; private final int

    age; Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (getAge() != person.getAge()) return false; return getName() != null ? getName().equals(person.getName()) : person.getName() == null; } @Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + getAge(); return result; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } 51 Lines
  16. struct Person { let name: String let age: Int }

    let dude = Person(name: "Dude", age: 21)
  17. data class Person( val name: String, val age: Int) val

    dude = Person(name = "Dude", age = 21)
  18. With the inessentials stripped out, you can structure your own

    code such that it reads as if it were using a DSL. “Code that reads like Pseudo Code”
  19. protocol Duck { func quack() -> String } extension Duck

    { func quack() -> String { return "quack" } }
  20. interface Duck { fun quack() = "quack" } class WeirdPerson:

    Person, Duck { } * This works in Java 8 too
  21. public class StringUtils { public static String developerize(String s) {

    return "Basically, " + s; } } StringUtils.developerize(“hello”)
  22. let bhais = persons .filter { $0.car.color == .red }

    .sorted(by: {$0.swag > $1.age}) .prefix(upTo: 3) .map { $0.name }
  23. val bhais = persons .filter { it.car.color == Color.RED }

    .sortedBy { it.swag } .take(3) .map { it.name }
  24. Car makeCarForBhai() { Car *car = Car(); car.color = Color.RED;

    car.installNitroBoost(); car.removeSilencer(); return car; }
  25. fun makeCarForBhai(): Car { return Car().apply { color = Color.RED

    installNitroBoost() removeSilencer() } } * Swift: The “Then” library
  26. • (Swift) Generics • (Kotlin) Better Generics • Lazy Properties

    • Observable Properties • Real Enumerations • (Kotlin) Try with Resource Blocks • (Swift) Booleans! • Ranges • String Interpolation • Operator Overloading • Easier Singletons
  27. @interface God: NSObject + (God *)sharedInstance; @end @implementation God +

    (God *)sharedInstance { static God *sharedInstance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[God alloc] init]; }); return sharedInstance; } @end * Almost
  28. class God { private static final God instance = new

    God(); private God() {} public static God getInstance() { return instance; } } * Almost
  29. class God { private static final God instance = null;

    private God() {} public static synchronized God getInstance() { if (instance == null) instance = new God(); return instance; } }
  30. 1. Create a “.swift” file Xcode: "Would You like to

    configure an Objective-C bridging Header"? You: Yes 2. Build Settings > Defines Module > Yes 3. #import "YourProjectName-swift.h"
  31. 1. Create a “.kt” file Android Studio: "Install Kotlin Plugin"?

    You: Yes 2. ⌘⇧A “Configure Kotlin in Project” 3. Gradle “Sync Now”
  32. Until Swift 4, your apps will embed the Swift runtime.

    Depending on the frameworks you use, this can be substantial increase in your binary size (think ~5 MB). ⚠ Dragons * Kotlin’s fine. ~900K pre-proguard.
  33. The Kotlin compiler is visibly slower than Java’s. Kotlin supports

    incremental builds, but your clean builds will take much longer once you have a lot of Kotlin files. ⚠ Dragons * Swift’s fine.