引用
英文原文:
目录
多平台项目 (实验性)
多平台项目是 kotlin 1.2 中的一个新的实验性功能,允许你在 kotlin – jvm, javascript 和(将来的)native 上所支持的目标平台之间重用代码。在多平台项目中,你有三种模块:
- 一个通用(common)的模块 —— 包含非特定于任何平台的代码,以及不附带依赖于平台的 api 实现的声明。
- 平台(platform)模块 —— 包含用于特定平台的通用模块中与平台相关声明的实现,以及其他平台相关代码。
- 常规(regular)模块针对特定的平台,可以是平台模块的依赖,也可以是依赖的平台模块。
在为特定平台编译多平台项目时,会生成通用及特定平台相关部分的代码。
多平台项目支持的一个关键特性是可以通过 expected 以及 actual 声明来表达通用代码对平台特定部分的依赖关系。expected 声明指定了一个 api(类、接口、注释、顶层声明等)。actual 声明或是 api 的平台相关实现,或是在外部库中 api 现有实现的别名引用。下面是一个示例:
在通用代码中:
// expected platform-specific api:
expect fun hello(world: string): string
fun greet() {
// usage of the expected api:
val greeting = hello("multi-platform world")
println(greeting)
}
expect class {
open fun gethost(): string
open fun getpath(): string
}
在 jvm 平台中,代码如下所示:
actual fun hello(world: string): string =
"hello, $world, on the jvm platform!"
// using existing platform-specific implementation:
actual typealias url = java.net.url
详细信息请参考,并按照步骤构建多平台项目。
其他语言特性
注解中的数组常量
从 kotlin 1.2 开始,注解的数组参数可以使用新的数组常量语法而不是 arrayof 函数来传递:
@cacheconfig(cachenames = ["books", "default"])
public class bookrepositoryimpl {
// ...
}
数组常量语法被限制为注释参数。
lateinit 顶级属性和局部变量
lateinit 修饰符现在可以用在顶级属性和局部变量上。例如,当一个 lambda 作为构造函数参数传递给一个对象时,后者可以用于引用另一个必须稍后定义的对象:
lateinit修饰符现在可以用在顶级属性和局部变量上。 例如,当作为构造函数参数传递给一个对象的 lambda 引用另一个对象时,稍后必须定义的对象可以使用:
class node(val value: t, val next: () -> node)
fun main(args: array) {
// a cycle of three nodes:
lateinit var third: node
val second = node(2, next = { third })
val first = node(1, next = { second })
third = node(3, next = { first })
val nodes = generatesequence(first) { it.next() }
println("values in the cycle: ${nodes.take(7).jointostring { it.value.tostring() }}, ...")
}
循环中的值:1, 2, 3, 1, 2, 3, 1, ...
目标平台:运行 kotlin 1.2.0 版本的 jvm
检查一个 lateinit 变量是否被初始化
现在可以在属性引用上使用 isinitialized 来检查 lateinit 变量是否已经被初始化:
class foo {
lateinit var lateinitvar: string
fun initializationlogic() {
println("isinitialized before assignment: " this::lateinitvar.isinitialized)
lateinitvar = "value"
println("isinitialized after assignment: " this::lateinitvar.isinitialized)
}
}
fun main(args: array) {
foo().initializationlogic()
}
isinitialized before assignment: false
isinitialized after assignment: true
目标平台:运行 kotlin 1.2.0 版本的 jvm
带默认函数参数的内联函数
内联函数现在允许其内联函数参数具有默认值:
inline fun iterable.strings(transform: (e) -> string = { it.tostring() }) =
map { transform(it) }
val defaultstrings = listof(1, 2, 3).strings()
val customstrings = listof(1, 2, 3).strings { "($it)" }
fun main(args: array) {
println("defaultstrings = $defaultstrings")
println("customstrings = $customstrings")
}
defaultstrings = [1, 2, 3]
customstrings = [(1), (2), (3)]
目标平台:运行 kotlin 1.2.0 版本的 jvm
来自显式类型的信息被用于类型推断
kotlin 编译器现在可以使用类型转换信息进行类型推断。如果调用一个返回类型参数 t 并将返回值转换为特定类型 foo 的泛型方法,则编译器现在可以理解此调用的 t 需要绑定到 foo 类型。
这对 android 开发者来说尤其重要,因为编译器现在可以在 android api level 26 中正确分析范型 findviewbyid 调用:
val button = findviewbyid(r.id.button) as button
改进 smart cast
当一个变量从一个安全调用表达式中被赋值并且被检查为 null 时,smart cast 也被应用到安全调用接收器中:
un countfirst(s: any): int {
val firstchar = (s as? charsequence)?.firstornull()
if (firstchar != null)
return s.count { it == firstchar } // s: any is smart cast to charsequence
val firstitem = (s as? iterable<*>)?.firstornull()
if (firstitem != null)
return s.count { it == firstitem } // s: any is smart cast to iterable<*>
return -1
}
fun main(args: array) {
val string = "abacaba"
val countinstring = countfirst(string)
println("called on \"$string\": $countinstring")
val list = listof(1, 2, 3, 1, 2)
val countinlist = countfirst(list)
println("called on $list: $countinlist")
}
called on "abacaba": 4
called on [1, 2, 3, 1, 2]: 2
目标平台:运行 kotlin 1.2.0 版本的 jvm
而且,现在允许在 lambda 中进行智能的强制转换,这些局部变量只在 lambda 之前被修改:
fun main(args: array) {
val flag = args.size == 0
var x: string? = null
if (flag) x = "yahoo!"
run {
if (x != null) {
println(x.length) // x is smart cast to string
}
}
}
目标平台:运行 kotlin 1.2.0 版本的 jvm
支持 ::foo 作为 this::foo 的缩写
现在可以使用 ::foo 替代 this::foo,写入一个绑定的可调用的引用,而不用明确的接收器。这也使得可调用的引用在你引用外部接收者的成员的 lambda 中更方便使用。
破坏性变更:try 块后面的 sound smart casts
早些时候,kotlin 使用了 try 块中的赋值,以在块之后进行 smart casts,这可能会破坏类型及 null 值的安全性并导致运行时失败。这个版本修复了此问题,使 smart casts 更严格,但破坏了一些依赖这种 smart casts 的代码。
要切换到旧的 smart casts 行为,传递 fallback 标志 -xlegacy-smart-cast-after-try 作为编译器参数。它将在 kotlin 1.3 中被弃用。
弃用:数据类的覆写性拷贝
当从已经具有相同签名的拷贝函数的类型派生数据类时,为数据类生成的 copy 实现使用父类型的默认函数,会导致出现与预期相反的行为,如果父类型没有默认参数,则在运行时失败
导致复制冲突的继承已经被 kotlin 1.2 中的警告所取代,并且在 kotlin 1.3 中这将会提示是错误的。
弃用:枚举项中的嵌套类型
在枚举项中,由于初始化逻辑中的问题,定义一个不是内部类的嵌套类型的功能已经被弃用。在 kotlin 1.2 中这将会引起警告,并将在 kotlin 1.3 中报错。
弃用:vararg 中的单命名参数
为了与注解中的数组常量保持一致,在命名的表单(foo(items = i)) 中为 vararg 参数传递的单项目已被弃用。请使用具有相应数组工厂函数的展开运算符:
foo(items = *intarrayof(1))
在这种情况下,有一种优化可以消除冗余数组的创建,从而防止性能下降。单一参数的表单在 kotlin 1.2 中会引起警告,并将在 kotlin 1.3 中被移除。
弃用:扩展 throwable 的泛型类的内部类
继承自 throwable 的泛型的内部类可能会违反 throw-catch 场景中的类型安全性,因此已被弃用,在 kotlin 1.2 中会被警告,在 kotlin 1.3 中将会报错。
弃用:改变只读属性的 backing 字段
在自定义 getter 中通过赋值 field = ... 来改变只读属性的 backing 字段已被弃用,在 kotlin 1.2 中会被警告,在 kotlin 1.3 中将会报错。
标准库
kotlin 标准库 artifacts 及拆分包
kotlin 标准库现在完全兼容 java 9 的模块系统,它会禁止对包进行拆分(多个 jar 包文件在同一个包中声明类)。为了支持这一点,引入了新的 artifacts kotlin-stdlib-jdk7 和 kotlin-stdlib-jdk8,取代了旧的 kotlin-stdlib-jre7 和 kotlin-stdlib-jre8。
新 artifacts 中的声明从 kotlin 的角度来看在相同的包名下可见的,但是对 java 而言它们有不同的包名。因此,切换到新的 artifacts 不需要对源代码进行任何更改。
确保与新模块系统兼容的另一个更改是从 kotlin-reflect 库中移除 kotlin.reflect 包中的弃用声明。如果使用它们,则需要使用 kotlin.reflect.full 包中的声明,自 kotlin 1.1 以来该包是被支持的。
windowed, chunked, zipwithnext
iterable
, sequence 和 charsequence 的新扩展包含了诸如缓冲或批处理(chunked),滑动窗口和计算滑动平均值 (windowed)以及处理 subsequent item 对 (zipwithnext) 等用例:
fun main(args: array) {
val items = (1..9).map { it * it }
val chunkedintolists = items.chunked(4)
val points3d = items.chunked(3) { (x, y, z) -> triple(x, y, z) }
val windowed = items.windowed(4)
val slidingaverage = items.windowed(4) { it.average() }
val pairwisedifferences = items.zipwithnext { a, b -> b - a }
println("items: $items\n")
println("chunked into lists: $chunkedintolists")
println("3d points: $points3d")
println("windowed by 4: $windowed")
println("sliding average by 4: $slidingaverage")
println("pairwise differences: $pairwisedifferences")
}
输出结果:
items: [1, 4, 9, 16, 25, 36, 49, 64, 81]
chunked into lists: [[1, 4, 9, 16], [25, 36, 49, 64], [81]]
3d points: [(1, 4, 9), (16, 25, 36), (49, 64, 81)]
windowed by 4: [[1, 4, 9, 16], [4, 9, 16, 25], [9, 16, 25, 36], [16, 25, 36, 49], [25, 36, 49, 64], [36, 49, 64, 81]]
sliding average by 4: [7.5, 13.5, 21.5, 31.5, 43.5, 57.5]
pairwise differences: [3, 5, 7, 9, 11, 13, 15, 17]
目标平台:运行 kotlin 1.2.0 版本的 jvm
fill, replaceall, shuffle/shuffled
添加了一系列扩展函数用于处理列表:针对 mutablelist 的 fill, replaceall 和 shuffle ,以及针对只读 list 的 shuffled:
fun main(args: array) {
val items = (1..5).tomutablelist()
items.shuffle()
println("shuffled items: $items")
items.replaceall { it * 2 }
println("items doubled: $items")
items.fill(5)
println("items filled with 5: $items")
}
shuffled items: [5, 3, 1, 2, 4]
items doubled: [10, 6, 2, 4, 8]
items filled with 5: [5, 5, 5, 5, 5]
目标平台:运行 kotlin 1.2.0 版本的 jvm
kotlin-stdlib 中的数学运算
为满足用户长期以来的需求,kotlin 1.2 中增加了用于数学运算的 kotlin.math api,也是 jvm 和 js 的通用 api,包含以下内容:
- 常量:pi 和 e
- 三角函数:cos, sin, tan 及其逆函数 acos, asin, atan, atan2
- 双曲三角函数:cosh, sinh, tanh 及其逆函数 acosh, asinh, atanh
- 指数函数:pow (扩展函数), sqrt, hypot, exp, expm1
- 对数函数:log, log2, log10, ln, ln1p
- round 函数:
ceil, floor, truncate, round (半值取偶)函数
roundtoint, roundtolong (半值取整)扩展函数
- 符号函数和绝对值:
abs 和 sign 函数
absolutevalue 和 sign 扩展属性
withsign 扩展函数
- 两个数值的 max 和 min
- 二分表示:
ulp 扩展属性
nextup, nextdown, nexttowards 扩展函数
tobits, torawbits, double.frombits (这些都位于 kotlin 包中)
同系列(但不包括常量)的函数也针对 float 型参数提供了。
biginteger 和 bigdecimal 的运算与转换
kotlin 1.2 引入了一组用于操作 biginteger 和 bigdecimal 以及使用从其他数字类型进行转换的函数。这些函数是:
- 用于 int 和 long 类型的 tobiginteger
- 用于 int, long, float, double, 和 biginteger 类型的 tobigdecimal
- 算术和位运算符函数:
二元运算符 , -, *, /, % 和中缀函数 and, or, xor, shl, shr
一元运算符 -, , -- 和一个函数 inv
浮点数转换
添加了新的函数,用于将 double 和 float 转换成位表示形式:
- tobits 和 torawbits 对于 double 类型返回 long,而对于 float 返回 int
- double.frombits 和 float.frombits 用于从位表示形式中转换为浮点数
regex 类现在是可序列化的
kotlin.text.regex 类已成为可序列化的类,现在可以在可序列化的层次结构中使用。
如果满足条件,closeable.use 可以调用 throwable.addsuppressed
在一些其他异常处理后,关闭资源期间抛出异常时,closeable.use 函数可调用 throwable.addsuppressed。
要启用这个行为,你需要在你的依赖关系中包含 kotlin-stdlib-jdk7。
jvm后端
构造函数调用标准化
自 1.0 以来,kotlin 开始支持复杂控制流的表达式,例如 try-catch 表达式和内联函数调用。根据 java 虚拟机规范这样的代码是合法的。不幸的是,当构造函数调用的参数中存在这样的表达式时,一些字节码处理工具不能很好地处理这些代码。
为了减少使用此类字节码处理工具的用户的这个问题,我们添加了一个命令行选项 (-xnormalize-constructor-calls=mode),它会告诉编译器为这样的结构生成更多的类 java 字节码。这里 mode 的值是以下之一:
- disable (默认值)—— 以和 kotlin 1.0 和 1.1 相同的方式生成字节码
- enable —— 为构造函数调用生成类 java 字节码。这可以改变类加载和初始化的顺序
- preserve-class-initialization —— 为构造函数调用生成类 java 字节码,以确保保持类初始化顺序。这可能会影响应用程序的整体性能;仅在多个类之间共享一些复杂的状态并在类初始化时更新时才使用它。
“手工”的解决方法是将控制流的子表达式的值存储在变量中,而不是直接在调用参数中对它们进行求值。它类似于 -xnormalize-constructor-calls=enable。
java 默认方法调用
在 kotlin 1.2 之前,接口成员在使用 jvm 1.6 的情况下重写 java 默认方法会在父调用中产生警告:super calls to java default methods are deprecated in jvm target 1.6. recompile with '-jvm-target 1.8'。在 kotlin 1.2 中,这将会报错,因此需要使用 jvm 1.8 来编译这些代码。
破坏性变更:平台类型的 x.equals(null) 一致行为
在映射到 java 原语 (int!, boolean!, short!, long!, float!, double!, char!) 的平台类型上调用 x.equals(null) 时,如果 x 为 null,则会不正确地返回 true。从 kotlin 1.2 开始,在平台类型的空值上调用 x.equals(...) 会抛出 npe(但 x == ... 时并不会)。
要返回到 1.2 之前的行为,请将 -xno-exception-on-explicit-equals-for-boxed-null 标志传递给编译器。
破坏性变更:通过内联的扩展接收器修复平台的 null 转义
在平台类型空值上调用的内联扩展函数并没有检查接收器是否为 null,并因此允许 null 转义到其他代码中。kotlin 1.2 在调用点强制执行此检查,如果接收方为空,则抛出异常。
要切换到旧行为,请将 fallback 标志 -xno-receiver-assertions 传递给编译器。
javascript 后端
默认启用对类型化数组(typedarrays)的支持
js typed arrays 支持将 kotlin 基本数组(如 intarray, doublearray)转换为 ,以前这是可选功能,现在默认情况下已启用。
工具
将警告视为错误
编译器现在提供了将所有警告视为错误的选项。在命令行中使用 -werror,或使用以下的 gradle 代码:
compilekotlin {
kotlinoptions.allwarningsaserrors = true
}
1 楼 2017-12-06 10:28