forked from gi-no/kotlin-is-like-typescript
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.html
967 lines (828 loc) · 36.6 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
<!DOCTYPE html><html><head><title>Kotlin is like TypeScript</title><meta charset="utf-8"><style>body {
font-family: "Helvetica Neue", sans-serif;
margin: 0;
}
body * {
box-sizing: border-box;
}
.section {
background-color: #f4f4f4;
padding: 4em 3em;
}
.section:nth-child(2n) {
background-color: white;
}
.title {
font-size: 2.7em;
color: #888;
font-weight: 100;
letter-spacing: 0.2em;
text-align: center;
}
.case {}
.name {
font-size: 1.8em;
color: #444;
font-weight: 300;
text-align: center;
margin: 60px;
}
.pair {
display: flex;
display: -webkit-flex;
display: -ms-flexbox;
justify-content: center;
-webkit-justify-content: center;
-ms-box-pack: center;
-ms-box-align: center;
}
.card {
flex: 1;
-webkit-flex: 1;
-ms-flex: 1;
max-width: 590px;
margin: 0 10px;
}
.lang {
font-size: 1.3em;
color: #666;
padding-bottom: 0;
font-weight: 200;
letter-spacing: 0.07em;
}
.code {
font-size: 1.15em;
background-color: white;
margin: 0.4em 0 0 0;
padding: 0.4em;
line-height: 1.3em;
}
.section:nth-child(2n) .code {
background-color: #f4f4f4;
}
#fork-me {
position: absolute;
right: 0;
}
#note {
font-size: 1.5em;
color: #fff;
text-align: center;
padding: 0.6em;
background: #414141;
font-weight: 300;
letter-spacing: 0.05em;
}
</style><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/github.min.css"><script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js"></script><script>hljs.initHighlightingOnLoad();</script></head><body><a target="_blank" href="https://github.com/linux-china/kotlin-is-like-typescript"><img id="fork-me" src="http://nilhcem.github.io/swift-is-like-kotlin/fork-me.png"></a><div id="note">Kotlin is like TypeScript</div><div class="section"><div class="title">BASICS</div><div class="case"><div class="name">Hello World</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>println("Hello, world!")
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>console.log("Hello, world!");
</code></pre></div></div></div><div class="case"><div class="name">Variables And Constants</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>var myVariable = 42
myVariable = 50
val myConstant = 42
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let myVariable = 42;
myVariable = 50;
const myConstant = 42;
</code></pre></div></div></div><div class="case"><div class="name">Explicit Types</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val explicitDouble: Double = 70.0
// Boolean
// Byte, Short, Int, Long, Float, Double, UByte, UShort, UInt, ULong
// String
// Any, Unit
// Nothing
// dynamic
external fun require(module:String): dynamic</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>const explicitDouble: number = 70;
// boolean
// number, bigint
// string
// any, void
// never
// undefined, unknown, null, Symbol, union: string|number, string|object
declare const welcome: any;</code></pre></div></div></div><div class="case"><div class="name">Type Inference</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val label = "The width is "
val width = 94
val widthLabel = label + width
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>const label = "The width is ";
const width = 94;
const widthLabel = label + width;
</code></pre></div></div></div><div class="case"><div class="name">Type Aliases</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>typealias Name = String;
typealias NameResolver = () -> String;</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>type Name = string;
type NameResolver = () => string;</code></pre></div></div></div><div class="case"><div class="name">Smart casts</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun demo(x: Any) {
if (x is String) {
print(x.length) // x is automatically cast to String
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function foo2(arg: unknown) {
if (typeof arg === "string") {
// We know this is a string now.
console.log(arg.toUpperCase());
}
}
</code></pre></div></div></div><div class="case"><div class="name">Equality</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//Structural Equality (‘==’), Referential equality (‘===’), .equals method
data class User(val id: Int, val nick: String)
fun testEquals() {
val first: Any = User(1, "linux_china")
val second: Any = User(1, "linux_china")
println(first == second) //true
println(first === second) //false, Referential different
println(first.equals(second)) //true
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>//Equals Operator ( == ), Strict Equals Operator ( === )
let a: any = 10;
let b: any = "10"
console.log(a == b); //true
console.log(a == b); //true
console.log(a === b); //false, type different</code></pre></div></div></div><div class="case"><div class="name">Nullable/NonNull/Nullish Coalescing</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val name1: String = "xx"
var name2: String? = null
fun testNullable() {
name2.length //illegal
name2?.length //nullable check
name2!!.length //you know that
}
// Elvis Operator
val name3 = name2 ?: "good";</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let name1: string = "xx"
let name2: string | null = null
name2.length //null check validation
let len = name2?.length //nullable check
name2!.length //you know that
//Nullish Coalescing
let x1 = name2 ?? "default value";</code></pre></div></div></div><div class="case"><div class="name">String Interpolation</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val apples = 3
val oranges = 5
val fruitSummary1 = "I have ${apples + oranges} pieces of fruit."
val fruitSummary2 = """I have ${apples + oranges} pieces of fruit."""
val fruitSummary3 = html("""I have ${apples + oranges} pieces of fruit.""")
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>const apples = 3;
const oranges = 5;
const fruitSummary1 = `I have ${apples + oranges} pieces of fruit.`;
const fruitSummary2 = html`I have ${apples + oranges} pieces of fruit.`;
</code></pre></div></div></div><div class="case"><div class="name">Range Operator</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val names = arrayOf("Anna", "Alex", "Brian", "Jack")
val count = names.count()
for (i in 0..count - 1) {
println("Person ${i + 1} is called ${names[i]}")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>import * as _ from 'lodash';
const names = ["Anna", "Alex", "Brian", "Jack"];
const count = names.length;
for (let i of _.range(0, count)) {
console.log(`Person ${i + 1} is called ${names[i]}`)
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
</code></pre></div></div></div><div class="case"><div class="name">Inclusive Range Operator</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>for (index in 1..5) {
println("$index times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>import * as _ from 'lodash';
for(let index of _.range(1, 6)) {
console.log(`${index} times 5 is ${index * 5}`)
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
</code></pre></div></div></div></div><div class="section"><div class="title">COLLECTIONS</div><div class="case"><div class="name">Arrays/List</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun main12() {
val shoppingList = arrayOf(
"catfish", "water",
"tulips", "blue paint"
)
shoppingList[1] = "bottle of water"
val freezeList = listOf("first", "second", "third")
val mutableList = mutableListOf("first", "second", "third")
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let shoppingList = ["catfish", "water",
"tulips", "blue paint"];
shoppingList[1] = "bottle of water";
</code></pre></div></div></div><div class="case"><div class="name">Set</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val set1 = setOf(1 , 2 , 3 , 4 , 3)
val mutableSet = mutableSetOf(1 , 2 , 3 , 4 , 3);
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let mySet = new Set(); //ES2015
mySet.add(1);
mySet.delete(1)</code></pre></div></div></div><div class="case"><div class="name">Stream/Sequence</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val wordsSequence = listOf("one", "two", "three", "four").asSequence()
val list2 = wordsSequence
.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
.toList()
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let words = ["catfish", "water", "tulips", "blue paint"];
let list2 = words.filter(word => {
return word.length > 3;
}).map(word => {
return word.length
});</code></pre></div></div></div><div class="case"><div class="name">Map</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val occupations = mutableMapOf(
"Malcolm" to "Captain",
"Kaylee" to "Mechanic"
)
occupations["Jayne"] = "Public Relations"
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let occupations = {
"Malcolm": "Captain",
"Kaylee": "Mechanic",
};
occupations["Jayne"] = "Public Relations";
</code></pre></div></div></div><div class="case"><div class="name">Tuple</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>// data class as Tuple in Kotlin
data class GasPrices(val a: Double, val b: Double, val c: Double)
fun main7() {
val price = GasPrices(3.59, 3.69, 3.79)
val (a, b, _) = price
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>type GasPrices = [number, number, number]
//Labeled Tuple
type Range = [start: number, end: number];
function main4() {
let price: GasPrices = [3.59, 3.69, 3.79]
let [a, b, c] = price;
}</code></pre></div></div></div><div class="case"><div class="name">Filter/Map/Reduce</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun main13() {
val shoppingList = arrayOf("catfish", "water", "tulips", "blue paint")
shoppingList.filter { it.startsWith("c") }
.map { it.length }
.reduce { acc, i -> acc + i }
shoppingList.filter { it.startsWith("c") }
.forEach(::println)
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let shoppingList2 = ["catfish", "water", "tulips", "blue paint"];
shoppingList2
.filter(item => item.startsWith("c"))
.map(item => item.length)
.reduce((acc, item) => acc + item)
shoppingList2
.filter(item => item.startsWith("c"))
.forEach(item => {
console.log(item)
})
</code></pre></div></div></div><div class="case"><div class="name">Empty Collections</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val emptyArray = arrayOf<String>()
val emptyMap = mapOf<String, Float>()
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>const emptyArray: string[];
const emptyDictionary: {[key: string]: number};
</code></pre></div></div></div></div><div class="section"><div class="title">FUNCTIONS</div><div class="case"><div class="name">Functions</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun greet(name: String, day: String): String {
return "Hello $name, today is $day."
}
greet("Bob", "Tuesday")
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function greet(name: string, day: string): string {
return `Hello ${name}, today is ${day}.`
}
greet("Bob", "Tuesday");
</code></pre></div></div></div><div class="case"><div class="name">Variable Number Of Arguments</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun sumOf(vararg numbers: Int): Int {
var sum = 0
for (number in numbers) {
sum += number
}
return sum
}
fun main3() {
sumOf(42, 597, 12)
// sumOf() can also be written in a shorter way:
fun sumOf(vararg numbers: Int) = numbers.sum()
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function sumOf(...numbers: number[]): number{
let sum = 0;
for (let number of numbers) {
sum += number;
}
return sum;
}
sumOf(42, 597, 12);
</code></pre></div></div></div><div class="case"><div class="name">Function Type</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun makeIncrementer(): (Int) -> Int {
val addOne = fun(number: Int): Int {
return 1 + number
}
return addOne
}
val increment = makeIncrementer()
increment(7)
// makeIncrementer can also be written in a shorter way:
fun makeIncrementer() = fun(number: Int) = 1 + number
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function makeIncrementer():(number) => number{
function addOne(number: number): number {
return 1 + number;
}
return addOne
}
let increment = makeIncrementer();
increment(7);
// makeIncrementer can also be written in a shorter way:
let makeIncrementer = () => (number: number) => 1 + number;
</code></pre></div></div></div><div class="case"><div class="name">Functional Interface</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun interface IntPredicate {
fun accept(i: Int): Boolean
}
val isEven = IntPredicate { it % 2 == 0 }
fun main() {
println("Is 7 even? - ${isEven.accept(7)}")
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (source: string, subString: string) {
let result = source.search(subString);
return result > -1;
};</code></pre></div></div></div><div class="case"><div class="name">Lambda/Arrow Function</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//lambda
val printText = { text: String ->
println(text)
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>//arrow function
let printText = (text: string) => {
console.log(text)
}</code></pre></div></div></div><div class="case"><div class="name">Named Arguments</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun area(width: Int, height: Int) = width * height
area(width = 2, height = 3)
// This is also possible with named arguments
area(2, height = 2)
area(height = 3, width = 2)
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function area({width, height}:{width:number, height:number}):number {
return width * height;
}
area({width: 2, height: 3});
</code></pre></div></div></div><div class="case"><div class="name">Function Generics</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>fun <T> identity(value: T): T {
return value
}
val str = identity("Hello")</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function identity<T>(value: T): T {
return value;
}
let str: string = identity<string>("Hello");</code></pre></div></div></div><div class="case"><div class="name">Generator Function</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val sequence2 = sequence {
val start = 0
// yielding a single value
yield(start)
// yielding an iterable
yieldAll(1..5 step 2)
// yielding an infinite sequence
yieldAll(generateSequence(8) { it * 3 })
}
println(sequence2.take(7).toList()) // [0, 1, 3, 5, 8, 24, 72]</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function* counter(max: number): Generator<number> {
let i = 0;
while (i < max) {
if (yield i++) {
break;
}
}
}
for (let num of counter(3)) {
console.log(num);
}
</code></pre></div></div></div><div class="case"><div class="name">Async Generator Function</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Collect the flow
simple().collect { value -> println(value) }
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>// async generator function
async function* g() {
yield 1;
await sleep(100);
yield* [2, 3];
yield* (async function*() {
await sleep(100);
yield 4;
})();
}
async function f() {
//The for-await-of Statement
for await (const x of g()) {
console.log(x);
}
}
</code></pre></div></div></div><div class="case"><div class="name">Optional/Default Value Params</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//Optional Parameters by default value
fun sayHello(name: String = "") {
}
fun main4() {
sayHello()
sayHello("Jackie")
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>// Optional Parameters
function sayHello(hello?: string) {
console.log(hello);
}
//default-initialized parameters
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
sayHello()
sayHello("Jackie")
buildName("Jack")
buildName("Jack", "Ma")
</code></pre></div></div></div><div class="case"><div class="name">Method Extension</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>import kotlin.js.RegExp
fun String.isEmailValid(): Boolean {
val pattern = RegExp("^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,8}$", "i")
return pattern.test(this)
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>declare interface String {
isEmailValid(): boolean;
}
String.prototype.isEmailValid = function (this: string): boolean {
let re = new RegExp("^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,8}$", 'i');
return re.test(this);
};</code></pre></div></div></div></div><div class="section"><div class="title">CLASSES</div><div class="case"><div class="name">Declaration</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>class Shape {
private var numberOfSides = 0
constructor(numberOfSides: Int) {
this.numberOfSides = numberOfSides
}
fun simpleDescription() =
"A shape with $numberOfSides sides."
}
val shape2 = Shape(4)</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>class Shape {
numberOfSides = 0;
constructor(numberOfSides: number) {
this.numberOfSides = numberOfSides;
}
simpleDescription(){
return `A shape with ${this.numberOfSides} sides.`;
}
}
let shape2 = new Shape(4)</code></pre></div></div></div><div class="case"><div class="name">Usage</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let shape = new Shape();
shape.numberOfSides = 7;
let shapeDescription = shape.simpleDescription();
</code></pre></div></div></div><div class="case"><div class="name">Subclass</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>open class NamedShape(val name: String) {
var numberOfSides = 0
open fun simpleDescription() =
"A shape with $numberOfSides sides."
}
class Square(var sideLength: BigDecimal, name: String) :
NamedShape(name) {
init {
numberOfSides = 4
}
fun area() = sideLength.pow(2)
override fun simpleDescription() =
"A square with sides of length $sideLength."
}
val test = Square(BigDecimal("5.2"), "square")
test.area()
test.simpleDescription()
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>class NamedShape {
numberOfSides: number = 0;
name: string;
constructor(name: string) {
this.name = name
}
simpleDescription():string {
return `A shape with ${this.numberOfSides} sides.`;
}
}
class Square extends NamedShape {
sideLength: number;
constructor(sideLength: number, name: string) {
super(name);
this.sideLength = sideLength;
this.numberOfSides = 4;
}
area(): number {
return this.sideLength * this.sideLength;
}
simpleDescription(): string {
return "A square with sides of length " +
this.sideLength + ".";
}
}
let test = new Square(5.2, "square");
test.area();
test.simpleDescription();
</code></pre></div></div></div><div class="case"><div class="name">Checking Type</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>var movieCount = 0
var songCount = 0
class Movie
class Song
fun main10() {
val library: List<Any> = listOf("first")
for (item in library) {
if (item is Movie) {
++movieCount
} else if (item is Song) {
++songCount
}
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>let movieCount = 0;
let songCount = 0;
class Movie {
}
class Song {
}
let library: unknown[] = [new Movie(), new Song()]
for (const item of library) {
if (item instanceof Movie) {
++movieCount;
} else if (item instanceof Song) {
++songCount;
}
}
</code></pre></div></div></div><div class="case"><div class="name">DownCasting</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>for (current in someObjects) {
if (current is Movie) {
println("Movie: '${current.name}', " +
"dir. ${current.director}")
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>for (let current in someObjects) {
if (current instanceof Movie) {
console.log(`Movie: '${movie.name}', ` +
`dir. ${movie.director}`);
}
}
</code></pre></div></div></div><div class="case"><div class="name">Protocol/Interface</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>interface Nameable {
fun name(): String
}
fun f<T: Nameable>(x: T) {
println("Name is " + x.name())
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>interface Nameable {
name(): string;
}
function f(x: Nameable) {
console.log("Name is " + x.name());
}
</code></pre></div></div></div><div class="case"><div class="name">Mixins</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//mixin in Kotlin just Kotlin interface
interface MyInterface {
val prop: Int // abstract
fun foo() {
print(prop)
}
}
class Child : MyInterface {
override val prop: Int = 29
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>// Disposable Mixin
class Disposable {
isDisposed: boolean = false;
dispose() {
this.isDisposed = true;
}
}
class SmartObject {
}
interface SmartObject extends Disposable {
}
applyMixins(SmartObject, [Disposable]);
let smartObj = new SmartObject();
smartObj.dispose();
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
// @ts-ignore
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
});
});
}
</code></pre></div></div></div><div class="case"><div class="name">Enums</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>enum class Direction {
NORTH, SOUTH, WEST, EAST
}
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>enum Direction {
NORTH, SOUTH, WEST, EAST
}
enum Arrow {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}</code></pre></div></div></div><div class="case"><div class="name">Annotations/Decorators</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,
AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class Fancy
@Fancy class Foo {
@Fancy fun baz(@Fancy foo: Int): Int {
return (@Fancy 1)
}
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>function enumerable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@enumerable(false)
greet() {
return "Hello, " + this.greeting;
}
}</code></pre></div></div></div><div class="case"><div class="name">Object expressions</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>val helloWorld = object {
val hello = "Hello"
val world = "World"
// object expressions extend Any, so `override` is required on `toString()`
override fun toString() = "$hello $world"
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>const helloWorld = {
name: (): string => {
return "";
}
}
</code></pre></div></div></div><div class="case"><div class="name">Object as Function/invoke operator/Hybrid Types</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>class Config {
operator fun invoke(): String {
return "invoke"
}
}
fun main5() {
val config = Config()
println(config())
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = (function (start: number) {
console.log("start")
}) as Counter;
counter.interval = 123;
counter.reset = function () {
};
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;</code></pre></div></div></div><div class="case"><div class="name">Indexed operator/Indexable Types</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//Indexed access operator
class StringArray {
operator fun get(index: Int): String {
return ""
}
operator fun set(index: Int, value: String) {
}
operator fun get(index: String): String {
return ""
}
operator fun set(index: String, value: String) {
}
}
fun main8() {
val stringArray = StringArray()
stringArray[0]
stringArray["first"] = "second"
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>//Indexed access operator
class StringArray {
operator fun get(index: Int): String {
return ""
}
operator fun set(index: Int, value: String) {
}
operator fun get(index: String): String {
return ""
}
operator fun set(index: String, value: String) {
}
}
fun main8() {
val stringArray = StringArray()
stringArray[0]
stringArray["first"] = "second"
}</code></pre></div></div></div><div class="case"><div class="name">Data Class</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>data class Point(val x: Double, val y: Double)
val point = Point(1.0, 2.0);
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>type Point = {
x: number,
y: number
}
let point: Point = {x: 1.0, y: 2.0};</code></pre></div></div></div><div class="case"><div class="name">readonly property</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//use val for readonly
data class Foo2(val bar: Double, val bas: Double)
fun main11() {
val foo2 = Foo2(1.0, 2.0)
foo2.bar = 2.0 //illegal
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>type Foo2 = {
readonly bar: number;
readonly bas: number;
};
const foo: Foo2 = {bar: 123, bas: 456};
foo.bar = 456; // illegal
</code></pre></div></div></div><div class="case"><div class="name">Generics</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>class Box<T>(val value: T) {
}
val box = Box<Double>(1.0)</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}
let x: Box<number> = new Box(1.0);</code></pre></div></div></div><div class="case"><div class="name">Dynamic keys</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>class MyClass {
private val store = mutableMapOf<String, Any>()
operator fun get(key: String): Any? {
return store[key]
}
operator fun set(key: String, value: Any) {
store[key] = value
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>interface DictionarySupport {
[index: string]: any;
}</code></pre></div></div></div></div><div class="section"><div class="title">Async</div><div class="case"><div class="name">Coroutines/Promise</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>suspend fun findNickById(id: Int): String {
return "nick $id"
}
suspend fun main() {
val nick = findNickById(1)
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>//Promise
const promise1 = new Promise<string>((resolve, reject) => {
resolve("good")
//reject(new Error('failed'));
});
promise1.then(value => {
console.log('Hi', value);
}).catch(error => {
console.log('Oops', error);
});
(async () => {
let value = await promise1
console.log(value)
})();
</code></pre></div></div></div><div class="case"><div class="name">Flow/Observable</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.onEach
fun findVip(): Flow<String> {
return arrayOf("first", "second").asFlow()
}
fun main2() {
findVip().onEach {
print(it)
}
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>import { from } from 'rxjs';
const result = from( [10, 20, 30]);
result.subscribe(x => console.log(x));
</code></pre></div></div></div></div><div class="section"><div class="title">Module/Namespace</div><div class="case"><div class="name">Namespace</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>package validation
import kotlin.js.RegExp
val zipCodeRegex = RegExp("[0-9]+")
interface StringValidator {
fun isAcceptable(s: String): Boolean;
}
class ZipCodeValidator : StringValidator {
override fun isAcceptable(s: String): Boolean {
return s.length == 5 && zipCodeRegex.test(s);
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>namespace Validation {
const numberRegexp = /^[0-9]+$/;
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string): boolean {
return s.length === 5 && numberRegexp.test(s);
}
}
}
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZipCode"] = new Validation.ZipCodeValidator();
</code></pre></div></div></div><div class="case"><div class="name">External Declare</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>@file:JsModule("lodash")
package lodash
@JsName("toUpper")
external fun toUpper(text: String): String
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>//index.d.ts
export = _;
export as namespace _;
declare const _: _.LoDashStatic;
declare namespace _ {
interface LoDashStatic {
}
}
</code></pre></div></div></div><div class="case"><div class="name">Module Export</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>@JsExport
@JsName("hello")
fun hello(name: String): String {
return "Hello name"
}</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>export function hello(name: string): string {
return `Hello ${name}!`
}</code></pre></div></div></div></div><div class="section"><div class="title">Tools/Library</div><div class="case"><div class="name">Unit Test</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>// testImplementation(kotlin("test-js")) in build.gradle.ts
import kotlin.test.Test
import kotlin.test.assertEquals
class DemoTest {
@Test
fun testBar() {
console.log("Hello World!")
assertEquals(4, 2 * 2)
}
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>// jest, ts-jest
test("hello test", () => {
console.log("hello test");
});</code></pre></div></div></div><div class="case"><div class="name">Tools</div><div class="pair"><div class="card"><div class="lang">markdown</div><pre class="code"><code>### Kotlin Tools
* Gradle: project build tool with dev server support
* dukat: Convert declarations(d.ts) to Kotlin external declarations</code></pre></div><div class="card"><div class="lang">markdown</div><pre class="code"><code>### TypeScript Tools
* npm/yarn: project build tool
* webpack: bundle your assets and dev-server support</code></pre></div></div></div></div><div class="section"><div class="title">Pros/Cons</div><div class="case"><div class="name">Pros</div><div class="pair"><div class="card"><div class="lang">Kotlin</div><pre class="code"><code>//When expression
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
// DSL
html {
head {
title {+"XML encoding with Kotlin"}
}
}
//Operator overloading: https://kotlinlang.org/docs/operator-overloading.html#unary-operations
//Delegated properties
class Example {
var p: String by Delegate()
}
</code></pre></div><div class="card"><div class="lang">TypeScript</div><pre class="code"><code>// tagged literal
const code = html`<span>xxx</span>`
//String Literal Types
type EventType = "click" | "mouseover";
// union
type TextOrNumber = string | number;
// tuple
let x2: [string, number] = ["hello", 10];
</code></pre></div></div></div></div></body></html>