Kotlin编程实践11章 其他

1、在代码中获取kotlin版本号

val v12 = KotlinVersion(major = 1,minor = 2)
val v1342 = KotlinVersion(1,3,41)
v12<KotlinVersion.CURRENT  //T
KotlinVersion(1,3,41)==KotlinVersion(major = 1,minor = 3,patch =41) //T
KotlinVersion.CURRENT.isAtLeast(major=1,min =3)//T

2、重复执行lambda表达式

repeat函数,指定次数从0开始

fun main(args:Array<String>){
  repeat(5){
    println("Counting:$it")
  }
}

Counting:0
Counting:1
Counting:2
Counting:3
Counting:4

3、强制when语句进行穷举

添加exhaustive属性

fun method(n:Int){
  when(n%3){
    0->println("$n%3 == 0")
    1->println("$n%3 == 0")
    2->println("$n%3 == 0")
    else->println("have a problem")
  }.exhaustive
}

exhaustive返回当前对象,因此kotlin编译器要求他必须覆盖所有情况。

4、测量代码经过的时间

masureTimeMills/measureNanoTime

var time = masureTimeMills{
  IntStream.rangeClosed(1,6)
    .map{doubleIt(it)}
    .sun()
}

masureTimeMills 调用了System.currentTimeMills()求了差值。

measureNanoTime同样但是用的是System.nanoTime

5、理解Random的随机行为

val value = Random.nextInt()  //Int.MIN_VALUE..Int.MAX_VALUE
val value = Random.nextInt(10)  //0..10
val value = Random.nextInt(5,10)  //5..10
val value = Random.nextInt(7..12)  //7..12
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容