从 Kotlin 到 Ruby
录制器:多语言 Kotlin 适配器(kotlinc + Java 驱动程序)。顶层函数可以录制。analyze 能识别 Ktor 和 Spring(Kotlin)的路由;Spring 相关内容参见 java.md。
语言结构
- 空安全:
String?-> 可能为nil;?.->&.;?:->||(当 false 不是合法值时)或.nil? ? d : x;!!-> 只有在录制的用例体现时,才抛出类似NoMethodError的错误。 - 错误:
require(cond) { msg }->raise ArgumentError, msg unless cond;check()->RuntimeError(IllegalStateException);error(msg)->raise msg。 - 数据类 ->
Data.define(值相等,用with实现copy)。 - 密封类 /
when->case ... in模式匹配,或按类进行case。 - 集合:
map/filter/fold/groupBy/associateBy/sumOf/joinToString->map/select/reduce/group_by/index_by/sum/join。listOf是不可变的:如果修改它属于 bug,就使用freeze。 - Ktor:
get("/x/{id}") { call.respond(HttpStatusCode.OK, x) }-> 路由 +render json:。
陷阱
- 数值陷阱与 Java 相同:
Int溢出会回绕,/向零截断,%的结果符号与被除数相同(remainder),roundToInt()把 .5 向正无穷方向舍入(2.5 -> 3,-2.5 -> -2)。 String.length按 UTF-16 码元计数;在 Ruby 返回nil的情况下,substring会抛出StringIndexOutOfBoundsException(->IndexError)。- 对字符串调用
toInt()会抛出NumberFormatException(->ArgumentError,与Integer(s)相同);toIntOrNull()->Integer(s, exception: false)。