Kotlin & C# A Comparison of Two Modern Languages Kirill Rakhman - - PowerPoint PPT Presentation

kotlin c
SMART_READER_LITE
LIVE PREVIEW

Kotlin & C# A Comparison of Two Modern Languages Kirill Rakhman - - PowerPoint PPT Presentation

Kotlin & C# A Comparison of Two Modern Languages Kirill Rakhman Syntax Properties Kotlin C# val immutable : String = "Hello" public string Immutable { get ; } = "Hello" ; var mutable : String = "World" public


slide-1
SLIDE 1

Kotlin & C#

A Comparison of Two Modern Languages

Kirill Rakhman

slide-2
SLIDE 2

Syntax

slide-3
SLIDE 3

Properties

public string Immutable { get; } = "Hello"; public string Mutable { get; set; } = "World"; public string Computed => "!"; val immutable: String = "Hello" var mutable: String = "World" val computed: String get() = "!"

Kotlin C#

slide-4
SLIDE 4

Classes & Constructors

public class Foo { public string Bar { get; } public int Baz { get; } public Foo(string bar, int baz) { Bar = bar; Baz = baz; } } class Foo( val bar: String, val baz: Int ) Kotlin C#

slide-5
SLIDE 5

Class Instantiation

public class Foo { ... } var foo = new Foo("A String", 42); class Foo( val bar: String, val baz: Int ) val foo = Foo("A String", 42) Kotlin C#

slide-6
SLIDE 6

Class Initialization Syntax

public class Foo { public string Bar { get; set; } public int Baz { get; set; } } Foo foo = new Foo { Bar = "A String", Baz = 42 }; class Foo( val bar: String, val baz: Int ) val foo = Foo( bar = "A String", baz = 42 ) Kotlin C#

slide-7
SLIDE 7

Primary Constructors

public class Foo(string bar, int baz) { public string Bar { get; } = bar; public int Baz { get; } = baz; } class Foo( val bar: String, val baz: Int ) Kotlin C# Planned for C# 6. Removed

slide-8
SLIDE 8

Data Classes / Records

public class Foo(string Bar, int Baz); var foo = new Foo("A String", 42); foo.With(Bar: "Another String") data class Foo( val bar: String, val baz: Int) val foo = Foo("A String", 42) foo.copy(bar = "Another String") Kotlin C# Planned for C# 7. Postponed

slide-9
SLIDE 9

Weird Tuple Hack

public class Person { public string Name { get; } public int Age { get; } public Person(string name, int age) => (Name, Age) = (name, age); } C#

slide-10
SLIDE 10

Scoping and Pattern Matching

slide-11
SLIDE 11

Let / Out Variables

Dictionary<string, string> dictionary = ... if (dictionary .TryGetValue("key", out string value)) { Console.WriteLine(value); } val map = mapOf<String, String>() map["key"]?.let { value -> println(value) }

Kotlin C#

slide-12
SLIDE 12

Let / Var Pattern

public string? GetValue() { … } if (GetValue() is string value) { Console.WriteLine(value); } fun getValue(): String? { … } getValue()?.let { value -> println(value) } Kotlin C#

slide-13
SLIDE 13

Out Variables & Pattern Matching

Dictionary<string, object> dictionary = ... if (dictionary .TryGetValue("key", out object value) && value is string s) { Console.WriteLine(s); } val map = mapOf<String, Any>() (map["key"] as? String)?.let { value -> println(value) }

Kotlin C#

slide-14
SLIDE 14

When / Switch

public string Format(object foo) { return foo switch { "0" => "Zero", string s => s.ToUpper(), (string a, string b) => $"({a}, {b})", _ => foo.ToString() }; } fun format(foo: Any): String { return when(foo) { "0" -> "Zero" is String -> foo.toUpperCase() is Pair<*,*> -> "(${foo.first}, ${foo.second})" else -> foo.toString() } } Kotlin C#

slide-15
SLIDE 15

Advanced Pattern Matching

static string Display(object o) => o switch { Point { X: 0, Y: 0 } p => "origin", Point { X: var x, Y: var y } p => $"({x}, {y})", _ => "unknown" }; C#

slide-16
SLIDE 16

Type System

slide-17
SLIDE 17

Nullable Reference Types

class Foo { string? bar; void DoThings(Thing? thing) { thing?.Call(); if (thing != null) thing.Call(); if (bar != null) bar.Split(""); } } class Foo { var bar: String? = null fun doThings(thing: Thing?) { thing?.call() if (thing != null) thing.call() if (bar != null) bar.split("") } }

Kotlin C#

slide-18
SLIDE 18

Nullable Structs

public struct Nullable<T> where T : struct { private T value; public bool HasValue { get; } } Nullable<int> foo = new Nullable<int>(); if (foo.HasValue) { ... } int? bar = null; if (bar != null) { … }

C#

slide-19
SLIDE 19

Refresher: Nothing Type

http://www.natpryce.com/articles/000818.html

slide-20
SLIDE 20

Nothing Typed Operators

public Foo(string? bar) { this.bar = bar ?? throw new ArgumentNullException(); } val nullableVariable: String? = null; val value: String = nullableVariable ?: throw Exception() val value: String = nullableVariable ?: return val value: String = nullableVariable ?: break val value: String = nullableVariable ?: continue val value: String = nullableVariable ?: exitProcess(0)

Kotlin C#

slide-21
SLIDE 21

Function Types, Lambdas, Method References

delegate string Format(int message); static void Foo(Format f) { … } static string IntToString(int x) => $"Number: {x}"; Foo(IntToString); Foo(x => x.ToString()); fun foo(f: (Int) -> String) { … } fun intToString(x: Int) = "Number: $x" foo(::intToString) foo { it.toString() } foo(Int::toString) Kotlin C#

slide-22
SLIDE 22

Function Types, Lambdas, Method References

static void Foo(Func<int, string> f) {} static string IntToString(int x) => $"Number: {x}"; Foo(IntToString); Foo(x => x.ToString()); fun foo(f: (Int) -> String) { … } fun intToString(x: Int) = "Number: $x" foo(::intToString) foo { it.toString() } foo(Int::toString) Kotlin C#

slide-23
SLIDE 23
slide-24
SLIDE 24
slide-25
SLIDE 25

Events

public delegate void EventHandler(object sender, EventArgs e); public event EventHandler ThresholdReached; // no initializer ThresholdReached += (sender, e) => { … } void OnThresholdReached(EventArgs e) { // Watch out for race conditions EventHandler handler = ThresholdReached; if (handler != null) { handler.Invoke(this, e); } }

C#

slide-26
SLIDE 26

Events

public delegate void EventHandler(object sender, EventArgs e); public event EventHandler ThresholdReached; ThresholdReached += (sender, e) => { … } void OnThresholdReached(EventArgs e) { ThresholdReached?.Invoke(this, e); }

C#

slide-27
SLIDE 27

Asynchronicity

slide-28
SLIDE 28

Couroutines / Async Await

async Task<string> GetFooAsync() { var s = await BarAsync(); return s.ToUpper(); } Task<string> BarAsync() => Task.FromResult("Hello"); suspend fun getFoo(): String { val s = bar() return s.toUpperCase() } suspend fun bar() = "Hello" Kotlin C#

slide-29
SLIDE 29

Asynchronous Branching

Task task = GetFooAsync(); // do things var foo = await task; val deferred = async { getFoo() } // do things val foo = deferred.await() Kotlin C#

slide-30
SLIDE 30

Async Parallelism

var results = await Task.WhenAll( GetFooAsync(), GetBarAsync()); val results = awaitAll( async { getFoo() }, async { getBar() }) Kotlin C#

slide-31
SLIDE 31

Forgetting to call await

slide-32
SLIDE 32

Cancellation

using var tokenSource = new CancellationTokenSource(); await DoThingsAsync(tokenSource.Token); tokenSource.Cancel(); async Task DoThingsAsync( CancellationToken token) { token.ThrowIfCancellationRequested(); // or if (token.IsCancellationRequested) return } val job = launch { doThings() } job.cancel() suspend fun doThings() { delay(100) coroutineScope { launch {} } yield() // or if (!isActive) return }

Kotlin C#

slide-33
SLIDE 33

Thx for Listening @Cypressious rakhman.info