Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Swift and Kotlin
Search
Manav
November 24, 2016
Programming
82
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Swift and Kotlin
If you write code in Objective C or Java, Swift and Kotlin will make you happy.
Manav
November 24, 2016
Other Decks in Programming
See All in Programming
Event is what happens
moro
2
790
コードレビューのボトルネックを"する側"と"される側"の両面から解消する
yub0n
2
1.6k
すこし踏み込む CancellationToken
htkym
2
1.7k
AWSに止められる覚悟してますか?
morizo_1984
2
540
外から家のPCの電源入れたい!をPHPで解決する
kawashimo0
1
130
[Dev Group Paris Octobre 26] Agentforce, SIforce, Claudeforce, Slackbot… on s'y retrouve ?
nabondance
0
110
なぜCTOを降りてFDEを選んだのか?〜なぜプロダクト企業がFDEで顧客の現場に踏み込むのか〜
gonta
1
210
phperだってパンチカードでコーディングしたい
o0h
PRO
0
340
IBM Bob Dojo #1 仕様駆動開発入門
oniak3ibm
PRO
0
390
カツオ、ご期待ください
suneo3476
0
190
R8 の設定見直しでアプリサイズ削減
andpad
0
220
UnityでSystem.Net.WebSocketsなWebSocketサーバが動かないのでUnity Monoのコードを覗いてみた / about implementing websocket server with unity mono
drumath2237
1
610
Featured
See All Featured
A designer walks into a library…
pauljervisheath
211
25k
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2.2k
Mind Mapping
helmedeiros
1
400
What does AI have to do with Human Rights?
axbom
PRO
1
2.5k
Designing for Timeless Needs
cassininazir
1
530
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
730
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
35
2.9k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
750
Agile Actions for Facilitating Distributed Teams - ADO2019
mkilby
0
310
Speed Design
sergeychernyshev
33
2.2k
The agentic SEO stack - context over prompts
schlessera
0
970
Designing Powerful Visuals for Engaging Learning
tmiket
1
610
Transcript
func main(args: Array<String>) { print("Hello, " + args[0]) } fun
main(args: Array<String>) { println("Hello, " + args[0]) }
If you write code in Objective C or Java, Swift
and Kotlin will make you happy.
Type Inference 1
DDXMLElement *element = [DDXMLElement elementWithName:@"iq"];
Packet packet = new Packet("iq");
DDXMLElement *element = [DDXMLElement elementWithName:@"iq"]; much element such long Wow
IDE
let element = DDXMLElement(name: "iq")
val packet = Packet("iq")
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")
The compiler will not let you write code that can
crash because of nulls. 2
NSURL *url = [NSURL URLWithString:myString]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSString *string = @”sunshine”; NSURL *url = [NSURL URLWithString:myString]; NSURLRequest
*request = [NSURLRequest requestWithURL:url];
None
let myString = "sunshine" let url = URL(string: myString) let
request = URLRequest(url: url)
None
struct URL { init?(string: String): URL? } struct URLRequest {
init(url: URL) }
// String -> URL? let url: URL? = URL(string: myString)
// URL -> URLRequest let request = URLRequest(url: url)
Guess what’s the Kotlin syntax
But it won’t get in your way when you write
the happy path. 3
person?.family?.meet()
let marriedGuy = person as? MarriedGuy if (marriedGuy) { marriedGuy.wife.family?.meet()
}
(person ?: otherPerson).family?.meet()
Bang bang when you know* it won’t bang bang. !!
* Are you sure?
Guess what’s the Kotlin syntax
Why is ?: called* the Elvis operator? Quiz * “Nil/Null
Coalescing”, cause Elvis is too cool for official documentation
guard let marriedGuy = person as? MarriedGuy else { return
“Did you even read the docs?” } marriedGuy.wife.family?.meet()
Kotlin kills it here
if (person !is MarriedGuy) { return “Did you even read
the docs?” } person.wife.family?.meet()
fun oh(missingPerson: Person?): String { if (missingPerson == null) {
return “Nobody’s missing” } return missingPerson.name() + “ got lost” }
when (x) { is Int -> print(x + 1) is
String -> print(x.length + 1) is IntArray -> print(x.sum()) } * Example taken from Kotlin docs
Why is less code better? Quiz
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.
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.
Lambdas 4
dispatch_async(queue, ^{ // do stuff });
Queue.async { // do stuff }
new Thread() { @Override public void run() { // do
stuff }; };
new Thread(() -> { // do stuff }); Java 8
/ Android with Retrolambda
Thread { // do stuff }
There is not even a single* spurious character. * Unless
you go Python
Unlike Java 8, Kotlin gives you “real” lambdas. PS:
Value Types 5
Is a person a value or a object? Why does
it matter? Quiz
@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
Objective C folks: Did we miss something? Quiz
@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
We done? Quiz
@implementation Person - (NSString *)description { return [NSString stringWithFormat: @"Person(name:
%@, age: %@)", self.name, @(self.age)]; } @end Total: 41 Lines
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
@Data class Person { private final String name; private final
int age; } Lombok!
struct Person { let name: String let age: Int }
let dude = Person(name: "Dude", age: 21)
data class Person( val name: String, val age: Int) val
dude = Person(name = "Dude", age = 21)
There is not a single spurious line.
What is the difference between equality and identity? Quiz Flashback
dude = = otherDude [dude isEqual:otherDude] Equality
dude = = = otherDude dude = = otherDude Identity
Guess what’s the Kotlin syntax
Who inspired Whom? Aside
What does “Kotlin” mean? Quiz
DSLs Meta
How hard do you think it is to implement CocoaPods
or Gradle? Quiz
Ruby Groovy Swift Kotlin Rake CocoaPods Capistrano Gradle
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”
Mixins 6
protocol Duck { func quack() -> String } extension Duck
{ func quack() -> String { return "quack" } }
struct WeirdPerson: Person, Duck { } Person().quack()
interface Duck { fun quack() = "quack" } class WeirdPerson:
Person, Duck { } * This works in Java 8 too
Extensions 7
public class StringUtils { public static String developerize(String s) {
return "Basically, " + s; } } StringUtils.developerize(“hello”)
Objective C audience right now
fun String.developerize() = "Basically, " + this “hello”.developerize()
NSInteger TDTIntegerSquare(NSInteger x) { return x * x; } TDTIntegerSquare(5);
extension Int { func square() -> Int { return self
* self } } 5.square()
Modern Standard Libraries 8
let bhais = persons .filter { $0.car.color == .red }
.sorted(by: {$0.swag > $1.age}) .prefix(upTo: 3) .map { $0.name }
val bhais = persons .filter { it.car.color == Color.RED }
.sortedBy { it.swag } .take(3) .map { it.name }
Seamless interop with Objective-C/Java collections types.
Swift has sugar for collections. Kotlin, unfortunately, doesn’t.
Random feature, so that Kotlin doesn’t feel bad...
Car makeCarForBhai() { Car *car = Car(); car.color = Color.RED;
car.installNitroBoost(); car.removeSilencer(); return car; }
fun makeCarForBhai(): Car { return Car().apply { color = Color.RED
installNitroBoost() removeSilencer() } } * Swift: The “Then” library
More goodies than one can pack in 10. Meta
• (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
Singletons 9
@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
class God { static let sharedInstance = God() } *
Almost
class God { static let sharedInstance = God() private init()
{} }
class God { private static final God instance = new
God(); private God() {} public static God getInstance() { return instance; } } * Almost
class God { private static final God instance = null;
private God() {} public static synchronized God getInstance() { if (instance == null) instance = new God(); return instance; } }
object God { }
The partying can start now! 10
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"
1. Create a “.kt” file Android Studio: "Install Kotlin Plugin"?
You: Yes 2. ⌘⇧A “Configure Kotlin in Project” 3. Gradle “Sync Now”
No Runtime Overhead Swift compiles to native code, Kotlin compiles
to JVM bytecode.
You can literally copy paste Java code from StackOverflow. Kotlin
Extras
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.
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.
Swift, because Apple. Kotlin, because Retrolambda+Lombok+Guava. Pragmatics
if (convinced) { manager.pester() } else { discuss(Date.now()) }
None