10 2020 档案
摘要:In Java, when you write code in try(...), if exception throw, the resource will be closed automactially: This is not necessary in Kotlin fun printFile
阅读全文
摘要:In java, it requires you to handle the exception when you declaring and using the code: public class BoringJavaCode { public static Double divide(int
阅读全文
摘要:List is not mutable, when you want to add data into list, you can do is: "adding data to a mutableList", then return a immutable list by calling toLis
阅读全文
摘要:The part pseudo class allows consumers of a web component to manipulate certain key elements inside the Shadow DOM. In this lesson we will explore two
阅读全文
摘要:document.getElementById("app").innerHTML = ` <h1>Hello Parcel!</h1> <div> <button id="plus">+</button> <button id="mius">-</button> </div> `; const ad
阅读全文
摘要:(0..9).forEach(::println) (9 downTo 0).forEach(::println) (0 until 9).forEach(::println) // 0 to 8 (0..9 step 2).forEach(::println) ('A'..'F').forEach
阅读全文
摘要:fun getColorType() : String { val color = getUpperFavoriteColor() return when (color) { "" -> "empty" "RED", "GREEN", "BLUE" -> "rgb" else -> "other"
阅读全文
摘要:Let function is another way to solve null problem in kotlin. When you have such problem: var favoriteColor: String? = null...... return if f(avoriteCo
阅读全文
摘要:In Javascript, we have: return age null ? -1 : age In kotlin, we can do the same thing with a better / simpler syntax: val safeAge: Int get() = age ?:
阅读全文
摘要:For data class, you can get 'copy' method, and also destructing: data class Customer (val name: String, val address: String, var age: Int) { // if we
阅读全文
摘要:// Shorter version class AnotherAlternativeCustomer (val name: String,var age: Int, val address: String = "") { var approvered: Boolean = false set(va
阅读全文
摘要:package com.rsk class Customer (val name: String, val address: String, var age: Int) { // if we don't want to pass in the address constructor(name: St
阅读全文
摘要:In this lesson, we use CSS transforms to create configurable 3D cuboids. Using CSS transforms in combination with scoped CSS variables, we are able to
阅读全文
摘要:In this lesson, we explore how you can use CSS variables almost like Boolean values in combination with calc(). By setting a variable to 1 or 0 and th
阅读全文
摘要:val randomNumber = Random().nextInt(3) if (randomNumber is BigDecimal) { result = result.add(BigDecimal(36)) } If you use type check, then 'result' is
阅读全文
摘要:Let's see following code: println(colors.reduce { acc, curr -> "$acc, $curr" }) // red, blue, green, black val myMap = mapOf(1 to "one", 2 to "two", 3
阅读全文
摘要:In kotlin, "fold" is same in Javascript's reduce. "fold" has initial value "reduce" in kotlin, you don't give initial value val colors = listOf("red",
阅读全文
摘要:import { curry, compose, toUpper, pipe } from 'ramda'; // #region listeners const _log = (value) => console.log(value); // #endregion // #region broad
阅读全文
摘要:Buffers give you chance to gather values together until your ready to work with them. This pattern can be used for calculations, string manipulations,
阅读全文
摘要:In our previous code, we have seen this partten for operators: // #region operators const concat = curry((broadcaster, listener) => { let string = '';
阅读全文
摘要:If you can think ahead to how you want your code to look into the future, then you can tackle your problems from the inside out. You design how you wa
阅读全文
摘要:import { curry } from 'ramda'; // #region listeners const _log = (value) => console.log(value); // #endregion // #region broadcasters const done = Sym
阅读全文
摘要:All good things come to an end. The concept of "done" plays a large part in our pattern and asynchronous code in general. We have to be able to handle
阅读全文
摘要:The patterns we've established can also work well with plain old Objects and Arrays. We just have to capture the behavior of accessing those values in
阅读全文
摘要:Functions returning functions returning functions can begin to look a bit unwieldy. The arrow function has helped the syntax a lot, but maybe using a
阅读全文
摘要:Functions returning functions returning functions can begin to look a bit unwieldy. The arrow function has helped the syntax a lot, but maybe using a
阅读全文
摘要:Remeber: each broadcast return a cancel function let createTimeout = (time) => (listener) => { let id = setTimeout(listener, time) return () => { clea
阅读全文
摘要:We should always ship fast experiences to our users, but sometimes something slips through our PR review process and our users start having a slow exp
阅读全文
摘要:For the follow code: function Cell({row, column}) { const state = useAppState() const cell = state.grid[row][column] const dispatch = useAppDispatch()
阅读全文
摘要:The way that context works is that whenever the provided value changes from one render to another, it triggers a re-render of all the consuming compon
阅读全文
摘要:const defaultInitialState = {status: 'idle', data: null, error: null} export function useAsync(initialState) { const initialStateRef = React.useRef({
阅读全文
摘要:// Window large lists with react-virtual // http://localhost:3000/isolated/final/04.js import React from 'react' import {useVirtual} from 'react-virtu
阅读全文
摘要:To understand lazy loading in React, we need to think in two steps. 1. Use dynamice import: to load script 2. Use React.lazy to load dynammice import,
阅读全文
摘要:Java way: package com.rsk.java; import java.util.function.Function; public class FPExample { public static Function<String, String> toSentenceCase = x
阅读全文
摘要:For example you have the Java class: package com.rsk.java; import com.rsk.kotlin.Customer; import com.rsk.kotlin.CustomerDatabase; import java.util.*;
阅读全文
摘要:npm install cookies-js --save import {Component, OnInit} from '@angular/core'; import {FormGroup, FormBuilder, Validators} from "@angular/forms"; impo
阅读全文
摘要:// course-detail.resolver.ts import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router"; import {Course} from "../shared/mod
阅读全文
摘要:For example we want to build pipe to sanitizer the url: @Pipe({ name: 'safeUrl' }) export class SafeUrlPipe implements PipeTransform { constructor(pri
阅读全文
摘要:buildscript { ext.kotlin_version = '1.1-M01' ext.kotlin_gradle_version = '1.1-M01' ext.mokito_kotlin_version = '0.6.0' ext.spek_version = '1.0.89' ext
阅读全文
摘要:Create a Kotlin class: package com.rsk.kotlin class Meeting(val title: String) { // in Java, you can use getLocation and setLocation var location = ""
阅读全文
摘要:Create a Java class: package com.rsk.java; import org.jetbrains.annotations.Nullable; public class Person { private String name; private int age; priv
阅读全文
摘要:package com.rsk interface Signatory { fun sign() } open class Person(val name: String, var age: Int, var isMarried: Boolean = false): Signatory { over
阅读全文
摘要:If your method is just a single line, it is good to use method expressions: interface Signatory { fun sign() } class Person: Signatory { override fun
阅读全文
摘要:In Kotlin, there is no static methods, but we can use companion object which works the same as static methods. For example, a class: package com.rsk i
阅读全文
摘要:First version: fun main(args: Array<String>) { val providers = Providers() val details = providers.getAllProviders() details.forEach { detail -> print
阅读全文
摘要:fun getAllProviders(fn: (String, String) -> Unit) { // Unit is just like void val allProviders = Providers.getProviders() val it = allProviders.iterat
阅读全文
摘要:fun main(args: Array<String>) { val ipToCount = mutableMapOf<String, Int>() File("src/ips.txt").forEachLine { val previous = ipToCount.getOrDefault(it
阅读全文
摘要:fun main(args: Array<String>) { val namesToAges = mapOf(Pair("Peter", 24), Pair("Roger", 42)) val namesToAges2 = mapOf( "Peter" to 24, "Roger" to 42 )
阅读全文
摘要:import java.io.File fun main(args: Array<String>) { File("src/inputFile.txt").forEachLine { print(it) // it refers to each line's content } }
阅读全文
摘要:var letters = str.toLowerCase().toCharArray().toHashSet()
阅读全文
摘要:onErrorResumeNext Will subscribe to each observable source it is provided, in order. If the source it's subscribed to emits an error or completes, it
阅读全文
摘要:import { fromEvent, timer } from 'rxjs'; import { throwIfEmpty, takeUntil } from 'rxjs/operators'; const click$ = fromEvent(document, 'click'); click$
阅读全文
摘要:import java.util.* fun main(args: Array<String>) { val number = Random().nextInt(100) + 1 var input: String? var guess = -1 while(guess!=number) { pri
阅读全文
摘要://vararg: just like ...args in js class Stack<T>(vararg val items: T) { val elements = items.toMutableList() fun push(element: T) { elements.add(eleme
阅读全文
摘要://vararg: just like ...args in js class Stack<T>(vararg val items: T) { val elements = items.toMutableList() fun push(element: T) { elements.add(eleme
阅读全文
摘要:In this lesson, we create a face for a head using layered comma-separated background images. CSS allows us to layer as many background images as we wa
阅读全文
摘要:
阅读全文
摘要:private protected internal: accessable for the project / module public https://kotlinlang.org/docs/reference/visibility-modifiers.html
阅读全文
摘要:import java.util.* class Animal { var age = 0 get() = field set(value) { if(value >= 0) { field = value } else { throw Error("bad number") } } } fun m
阅读全文
摘要:enum class Color { RED, GREEN, BLUE } fun main() { println(Color.GREEN) // GREEN } Or give enum a value: enum class Color { RED(0xFF0000), GREEN(0x00F
阅读全文
摘要:Singleton Object need to be defined as global variable: object Cache { val name= "Cache" fun retrieveDate(): Int { return 0 } } fun main() { println(C
阅读全文
摘要:If we want to use Class to represent a piece of data such as Object, we can use Data class instead of normal class. Difference: Data class has better
阅读全文
摘要:interface Lendable { fun borrow() } // The properties title, genre, and publicationYear can be included in the parent class because both books and DVD
阅读全文
摘要:import java.util.* /** * You can edit, run, and share this code. * play.kotlinlang.org */ abstract class Course(val topic: String, val price: Double)
阅读全文
摘要:import java.util.* /** * You can edit, run, and share this code. * play.kotlinlang.org */ interface Driveable { fun drive() } interface Buildable { va
阅读全文
摘要:open class Person (open val name: String = "", open var age: Int) { init {} open fun greeting(pn: String) { println("$name says hello to $pn") } } cla
阅读全文
摘要:class Person (val name: String, var age: Int) { init {} fun greeting(pn: String) { println("$name says hello to $pn") } } fun main() { val p = Person(
阅读全文
摘要:fun reverse(numbers: List<Int>): List<Int> { var res = arrayListOf<Int>() for (i in 0..numbers.size-1) { res.add(numbers.get(numbers.size - 1 - i)) }
阅读全文
摘要:It is possible to give loop a name, it is useful when dealing with nested loop: fun main() { outer@ for (i in 1..10) { for (j in 1..10) { if (i - j ==
阅读全文
摘要:fun main() { val list = listOf("Java", "Kotlin", "Python") for (element in list) { println(element) } for ((index, value) in list.withIndex()) { print
阅读全文
摘要:Array is mutable, but fixed length. Which means you can modify items in the Array, but you cannot add / remove item; // Array is fixed length, you can
阅读全文
摘要:Difference between "when" and Javascript "switch". In Switch, you have to call "break"; but "when", you don't need to. In Switch, the case expression
阅读全文
摘要:fun main() { val mode = 2 val result = when (mode) { 1 -> "1 is ok" 2 -> { println("2 is fine") val i: Int = 3 "return string 2 is fine" } else -> "la
阅读全文
摘要:fun main() { val mode = 3 when (mode) { 1 -> print("1 is ok") 2 -> { print("2 is fine") print("2 is fine") } else -> { print("large than 2 is not ok")
阅读全文
摘要:In Kotlin, it helps to avoid null reference, which means by default you cannot assign null value to any variable; But if you do want to assign null to
阅读全文
摘要:fun main() { val a = 4 val b: Byte = 127 val c: Short = 123 val d: Int = 7 val e: Long = 123456789 val f: Float = 3.73f val g: Double = 3.73 val h: Ch
阅读全文
摘要:using 'var', variable can be reassigned. using 'val', variable cannot be ressiagned. the same as Javascript 'const'.
阅读全文
摘要:Sometime when you create a library, you want types create automatcially for you, instead of typing all the types information by yourself. // tsconfig.
阅读全文
摘要:In lodash, you can use 'mixin' to create a new function on lodash object. import * as _ from 'lodash'; _.chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]] _.m
阅读全文
摘要:Instead of first checking to see if a record already exists within your table, we can do a on conflict do update. In this command, we can ether insert
阅读全文
摘要:The useDebugValue hook will not effect your user experience but is instead aimed at improving the developer experience. When building your own custom
阅读全文
摘要:function reverse(str: string): string; function reverse<T>(arr: T[]): T[]; function reverse<T>(stringOrArray: string | T[]): string | T[] { if (typeof
阅读全文
摘要:class Pizza { constructor(private name: string, private price: number) {} } class List<T> { private list: T[]; addItem(item: T): void { this.list.push
阅读全文
摘要:Discriminated (Tagged) Unions means that for two or more similar types, we have one common prop which can differentiate individual. interface Order {
阅读全文
摘要:interface Order { id: string; amount: number; currency: string; } interface Stripe { card: string; cvc: string; } interface PayPal { email: string; }
阅读全文
摘要:When we use class extend in typescript: // app.ts export default class App {} // bar.ts export defulat class Bar extends App { } After compiling, we w
阅读全文
摘要:tsconfig.json: { "compilerOptions": { "target": "es5", "lib": ["es6", "dom"], "module": "commonjs", "outDir": "dist", "noUnusedLocals": true, "noUnuse
阅读全文
摘要:Sometime if our tsconfig.json looks like this; { "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "dist" } } We can get all kinds
阅读全文
摘要:tsconfig-base.json: { "compilerOptions": { "target": "es5", "module": "commonjs", "lib": ["dom", "es6"], "outDir": "dist", "noImplicitAny": false } }
阅读全文
摘要:class Song { constructor(public title: string, public duration: number) { } } class Playlist { constructor(public name: string, public songs: Song[])
阅读全文
摘要:class Foo { bar() {} } const bar = new Foo() console.log(bar instanceof Foo) // true console.log(Object.getPrototypeOf(bar) Foo.prototype) // true cla
阅读全文
摘要:"Record" repersent key-value pair. type MyRecord<K extend string, T> = { [P in K]: T } Record key should be string. array[0] in javascript, even we gi
阅读全文
摘要:For example we have interface: interface Person { name: string, age?: number } 'age' is an optional prop. // will have an error since person.age is us
阅读全文
摘要:type MyPartial<T> = { [P in keyof T]?: T[P] } 'in' like a loop. Usage: function updatePerson(person: Person, prop: MyPartial<Person>) { return {...per
阅读全文
摘要:interface Person { name: string; age: number; address: {} } // gives error since we didn't define 'address' const person: Person = { name: "Wan", age:
阅读全文
摘要:interface Person { name: string; age: number; } interface ReadonlyPerson { readonly name: string; readonly age: number; } const person: ReadonlyPerson
阅读全文