美文网首页
Kotlin编程实践11章 其他

Kotlin编程实践11章 其他

作者: flynnny | 来源:发表于2021-12-30 03:51 被阅读0次

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

相关文章

网友评论

      本文标题:Kotlin编程实践11章 其他

      本文链接:https://www.haomeiwen.com/subject/mozbqrtx.html