02
Dev.to Kotlin
作者:Gabriel Anhaia
發布:05-03 09:29
Kotlin `apply` / `also` / `with` Don’t Translate Directly to TypeScript
TypeScript ships none of Kotlin’s scope functions, and almost nobody misses them.
重點摘要
Use object literals instead of `User().apply { ... }` for plain data.
Use `tap`, builders, or `Object.assign` only when the problem truly needs them.
`let` and `with` usually map to optional chaining, inline access, destructuring, or pipe-style functions.
Kotlin scope functions such as `let`, `also`, `apply`, and `with` are central to JVM-style code, but they do not have a one-to-one translation in TypeScript. The article shows that most `apply` use cases become object literals, while real staged construction can use fluent builders that return `this`. `also` maps cleanly to a small `tap` helper or a named temporary variable, and `with`/`run` are usually replaced by inline property access, destructuring, or a function expression. The core point is cultural as much as technical: TypeScript already has object literals, structural typing, spread, destructuring, and arrow functions, so developers should favor idiomatic TypeScript patterns instead of translating Kotlin habits literally.
Kotlin 的 `apply`/`also`/`with` 不要直接翻译成 TypeScript
TypeScript 没有 Kotlin 的 scope functions,而且大多数情况下也不需要。
重點摘要
普通数据初始化,直接用对象字面量代替 `User().apply { ... }`。
需要副作用时,可用 `tap`、命名临时变量或真正的 builder。
`let`、`with` 通常对应 optional chaining、解构、直接访问或 pipe。
Kotlin 的 `let`、`also`、`apply`、`with` 等 scope functions 在 JVM 生态里很常见,但在 TypeScript 中并没有一一对应的写法。文章说明,`apply` 大多数场景其实就是对象字面量;只有在真正分步骤构建对象时,才适合使用返回 `this` 的 fluent builder。`also` 可以用一个简单的 `tap` helper 或临时变量替代,而 `with`、`run` 往往会被内联属性访问、解构或函数表达式取代。核心不只是语法映射,更是习惯迁移:TypeScript 已经具备对象字面量、结构类型、spread、解构和箭头函数,应优先采用本地惯用模式。
Kotlin 的 `apply`/`also`/`with` 不應直接翻成 TypeScript
TypeScript 沒有 Kotlin 的 scope functions,而且幾乎也不需要它們。
重點摘要
一般資料初始化,直接用物件字面值取代 `User().apply { ... }`。
需要副作用時,可用 `tap`、命名暫存變數或真正的 builder。
`let`、`with` 多半對應到 optional chaining、解構、直接存取或 pipe。
Kotlin 的 `let`、`also`、`apply`、`with` 等 scope functions 在 JVM 世界很常用,但搬到 TypeScript 時並沒有一對一對應。文章指出,`apply` 多數情境其實就是物件字面值;若真有分 चरण式建構需求,才用回傳 `this` 的 fluent builder。`also` 可用簡單的 `tap` helper 或暫存變數替代,而 `with`、`run` 通常會被內聯屬性存取、解構或函式表達式取代。重點不只是語法轉換,更是思維切換:TypeScript 已有物件字面值、結構型別、spread、解構與箭頭函式,應優先採用本地慣用寫法。