欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Kotlin 基本语法实例详解

程序员文章站 2024-02-15 13:04:58
基本语法示例 实例代码: package com.stone.basic.syntax /** * desc : * author: stone...

基本语法示例

实例代码:

package com.stone.basic.syntax

/**
 * desc :
 * author: stone
 * email : aa86799@163.com
 * time : 27/05/2017 11 01
 */
class basicsyntax {

  //function having two int parameters with int return type:
  public fun sum(a: int, b: int): int {//访问修饰符 省略时,默认为 public
    return a + b
  }

  //function having three int parameters with int return type:
  fun sum(a: int, b: int, c: int) = a + b + c

  //function returning no meaningful value:
  fun printsum(a: int, b: int): unit {//unit为无类型,类似java中的void,可以省略
    println("sum of " + a + " and " + b + " is ${a + b}")
    println("sum of $a and $b is ${a + b}") //在双引号中 直接用 $符操作变量  与上句等价
  }

  fun assignvarible() {
    val a: int = 1 // immediate assignment  val = 本地只读变量 即不可变 immutable
    val b = 2 // `int` type is inferred 自动类型推断
    val c: int // type required when no initializer is provided
    c = 3 // deferred assignment

    var x = 1 // mutable variable:
    x++

    val s1 = "x is $x" // simple name in template:
    val s2 = "${s1.replace("is", "was")}, but now is $x" // arbitrary expression in template:
    println(s2)
  }

  fun maxof(a: int, b: int): int {
//    return a > b ? a : b; //原java中的三目运算符 不可用

    if (a > b) return a
    else return b
  }

  //fun maxof(a:int, b: int):int
  fun minof(a: int, b: int): int = if (a < b) a else b

  //字符串转int
  private fun parseint(str: string): int? {// ? 表示可以为空
    return str.tointornull(8)//参数为 进制数(radix), 不传默认为10  转换错误 返回null
  }

  fun getbasesyntax(name: string?): basicsyntax? { // ? 表示可以为空
//    checknotnull(name) // 参数不能为空的 检测函数
    return basicsyntax()
  }

  fun printproduct(arg1: string, arg2: string) {
    val x1 = parseint(arg1)
    val x2 = parseint(arg2)
    if (x1 == null) return
    if (x2 == null) return
    println(x1 * x2)
  }

  //is operator
  fun getstringlength1(obj: any): int? { //any 是任何kotlin类的超类
    if (obj is string) {// 类似java中的 instanceof
// `obj` is automatically cast to `string` in this branch
      return obj.length
    }
// `obj` is still of type `any` outside of the type-checked branch
    return null
  }

  // !is
  fun getstringlength2(obj: any): int? {
    if (obj !is string) return null
    return obj.length
  }

  fun getstringlength3(obj: any): int? {
    if (obj is string && obj.length > 0)
      return obj.length
    return null
  }

  //using a for loop
  fun foreachitems() {
//    val items = listof<string>("apple", "banana", "kiwi")
    val items = listof("apple", "banana", "kiwi")
    for (item in items) {//in operator
      println("item is $item")
    }
    for (index in items.indices) {//indices 索引 type: collection
//      println("item at $index is ${items.get(index)}")
      println("item at $index is ${items[index]}") //使用[index] 而不用 .get(index)
    }
  }

  //using when expression
  fun describe(obj: any): string =
      when (obj) {//when 中 必须 有一个else
        1 -> "one"
        "hello" -> "greeting"
        is long -> "long"
        !is string -> "not a string"
        else -> "unknown"
      }

  //using ranges 如果在if中 check的是一个数值,且使用了 in operator
  fun range() {
    val x = 10; val y = 9 //同一行中使用 ; 来分隔
    if (x in 1..y + 1) {//使用 .. 来表示范围  最后转换成 x in 1..10
//    if (x in (1..(y + 1))) {//如此解释 执行顺序 没问题 最后转换成 x in 1..10
//    if (x in ((1..y) + 1)) {如此解释 执行顺序 不行  最后转换成 x in 10
      println("fits in range")
    }

    for (x in 1..5) {//include 5

    }

    for (x in 1..10 step 2) {//x+=2  x is in {1, 3, 5, 7, 9}
      println("rang 1..10 step 2: $x")
    }

    for (x in 9 downto 0 step 3) {//x=9, x>=0 x-=3
      println("x in 9 downto 0 step 3: $x")
    }

    for (x in 0 until 10 step 2) {//until 10 : not include 10
      println("x in 1 until 10: $x")
    }
  }

  //checking if a collection contains an object using in operator:
  fun contains() {
    val list = listof("a1", "a2", "a3") //不可变list
    when {// 匹配到一个条件 其它 就不再匹配
      "a4" in list -> println("壹")
      "a5" in list -> println(list.size)
      "a3" in list -> println("the index is ${list.indexof("a3")}")
    }
  }

  //using lambda expressions to filter and map collections:
  fun collectionslambda() {
//    val list = mutablelistof<int>() //可变list
//    for (i in 1 ..10) {
//      list.add(i)
//
//    }

    val list = (1..10).tolist() //上面的 简写
    list.filter { it % 2 == 0 }.map { it * 3 }.foreach(::println)
//   list.filter { it % 2 == 0 }.map { it * 3 }.foreach{ println("item is $it")}
  }
}

fun main(args: array<string>) {
  var base = basicsyntax()

  base.printsum(10, 20)

  base.assignvarible()

  var min = base.minof(10, 20)
  println("min number is $min")

  base.getbasesyntax(null)

  base.printproduct("1", "kk")
  base.printproduct("33", "66")

  println(null) //直接输出了 null 字符串

  base.foreachitems()

  println(base.describe(2))

  base.range()

  base.contains()

  base.collectionslambda()

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!