Skip to content

Instantly share code, notes, and snippets.

View Meodinger's full-sized avatar
🐟
Fish-touching

王川瀚彧 Meodinger

🐟
Fish-touching
View GitHub Profile
@Meodinger
Meodinger / AssignOnce.kt
Last active March 24, 2022 03:59
A delegate that make the variable can only be assigned once
/**
* Can assign only once
*/
class AssignOnce<T> {
private var _backing: T? = null
operator fun getValue(thisRef: Any, property: KProperty<*>) = _backing!!
operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
synchronized(this) {
@Meodinger
Meodinger / try-with-resources.kt
Last active December 12, 2021 04:18
Kotlin try-with-resources
/**
* Kotlin try-with-resources practice
* All streams want to be auto-closed should run `autoClose()`
* Simple as origin syntax!
*/
inline fun using(crossinline block: ResourceManager.() -> Unit): Catcher {
val manager = ResourceManager()
try {
// Use manager's auto close
manager.use(block)
@Meodinger
Meodinger / _if_.kt
Last active October 7, 2024 12:00
Kotlin if-implicit-boolean-conversion
/**
* Support implicit conversion form Any? to boolean
* Use JavaScript standard
* Example: (_if_({ null }) { 0 } _else_ { 1 })() -> 1
*/
open class _if_<T>(private val condition: () -> Any?, private val ifBlock: () -> T) {
companion object {
fun Any?.logic(): Boolean {
return when (this) {
@Meodinger
Meodinger / Promise.kt
Last active December 12, 2021 04:21
Kotlin Promise
/**
* Kotlin Promise
* Just like the Promise in JavaScript
* Aplha Standard
*/
typealias Resolve<T> = (T) -> Unit // T : Any?
typealias OnResolved<T, R> = (T) -> R // T, R : Any?
typealias Reject<U> = (U) -> Unit // U : Throwable
typealias OnRejected<U, V> = (U) -> V // U, V : Throwable