首页 > 开发 > 综合 > 正文

分分钟学会Kotlin语言(Learn kotlin in Y Minutes)

2024-07-21 23:03:36
字体:大 中 小
来源:转载
供稿:网友
谷歌宣布kotlin成安卓开发一级语言以后,kotlin大热,Kotlin是JVM上的静态类型的编程语言,它是100%兼容的java。

废话少说,上代码,由于代码太长,分两段:

  1. //这是单行注释 // 
  2. /* 
  3. 这是多行注释 
  4. */ 
  5. // 这和Java的 "package" 差不多. 
  6. package com.learnxinyminutes.kotlin 
  7.  
  8. /* 
  9. Kotlin程序入口函数是名为"main". 
  10. 这个函数的入参是包含命令行参数的数组 
  11. */ 
  12. fun main(args: Array<String>) { 
  13.     /* 
  14.     声明值是使用"var" 或 "val". 
  15.     "val"是一旦分配值后就不能变,不变量,相反"vars" 是声明变量 
  16.     */ 
  17.     val fooVal = 10 // 之后就不能再给fooVal分配其他值了 
  18.     var fooVar = 10 
  19.     fooVar = 20 // fooVar是变量,能够再次分配值 
  20.  
  21.     /* 
  22.     大多数情况, Kotlin能够决定一个变量的类型是什么。 
  23.     这样我们不必显式明确每次去指定变量类型了。 
  24.     我们可以通过如下方式明确定义变量类型: 
  25.     */ 
  26.     val foo : Int = 7 
  27.  
  28.     /* 
  29.     Kotlin包含两种类型的字符串:与Java字符串相同的escaped strings和新的raw strings, 
  30.     escaped strings中的换行符是/n字符串和Java中一样定义, 
  31.     反斜杠是换行符 
  32.     */ 
  33.     val fooString = "My String Is Here!" 
  34.     val barString = "Printing on a new line?/nNo Problem!" 
  35.     val bazString = "Do you want to add a tab?/tNo Problem!" 
  36.     println(fooString) 
  37.     println(barString) 
  38.     println(bazString) 
  39.  
  40.     /* 
  41.     行字符串(raw strings)由三个引号分隔 ("""). 
  42.     顾名思义能包含新的一行和其他任何字符。 
  43.    下面是给fooRawString赋值的是一个函数helloWorld,直至第四行的三个引号才表示赋值结束 
  44.     */ 
  45.     val fooRawString = """ 
  46. fun helloWorld(val name : String) { 
  47.    println("Hello, world!") 
  48. } 
  49. """ 
  50.     println(fooRawString) 
  51.  
  52.     /* 
  53.     字符串能保护模板表达式 
  54.     模板表达式是以美元符号开始($). 
  55.     */ 
  56.     val fooTemplateString = "$fooString has ${fooString.length} characters" 
  57.     println(fooTemplateString) 
  58.  
  59.     /* 
  60.     对于一个变量是空必须明确指定其是nullable. 
  61.     变量可以在其类型后面追加问号?指定其是nullable, 
  62.     然后使用?.操作符访问这个nullable的变量 
  63.     也可以使用?: 操作符在其为null时为其分配一种值。 
  64.     */ 
  65.     var fooNullable: String? = "abc" 
  66.     println(fooNullable?.length) // => 3 
  67.     println(fooNullable?.length ?: -1) // => 3 
  68.     fooNullable = null 
  69.     println(fooNullable?.length) // => null 
  70.     println(fooNullable?.length ?: -1) // => -1 
  71.  
  72.     /* 
  73.     函数是使用"fun" 定义 
  74.     函数参数在函数名后面的括号中指定。函数参数可以有默认值。如果需要,函数返回类型在参数之后指定。 
  75.     */ 
  76.     fun hello(name: String = "world"): String { 
  77.         return "Hello, $name!" 
  78.     } 
  79.     println(hello("foo")) // => Hello, foo! 
  80.     println(hello(name = "bar")) // => Hello, bar! 
  81.     println(hello()) // => Hello, world! 
  82.  
  83.     /* 
  84.     一个函数参数可以使用"vararg" 标注, 
  85.     能够让许多参数传递进入函数。 
  86.     */ 
  87.     fun varargExample(vararg names: Int) { 
  88.         println("Argument has ${names.size} elements") 
  89.     } 
  90.     varargExample() // => Argument has 0 elements 
  91.     varargExample(1) // => Argument has 1 elements 
  92.     varargExample(1, 2, 3) // => Argument has 3 elements 
  93.  
  94.     /* 
  95.     当一个函数由单个表达式组成时,那么这个卷括号可以被省略。函数内容体是在等于号=之后指定。 
  96.     */ 
  97.     fun odd(x: Int): Boolean = x % 2 == 1 
  98.     println(odd(6)) // => false 
  99.     println(odd(7)) // => true 
  100.  
  101.     // 如果返回类型能被推断,我们就不必指定了。 
  102.     fun even(x: Int) = x % 2 == 0 
  103.     println(even(6)) // => true 
  104.     println(even(7)) // => false 
  105.  
  106.     // 函数能用函数作为参数,返回页首函数。 
  107.     fun not(f: (Int) -> Boolean): (Int) -> Boolean { 
  108.         return {n -> !f.invoke(n)} 
  109.     } 
  110.     // Named函数能使用 :: 作为参数指定. 
  111.     val notOdd = not(::odd) 
  112.     val notEven = not(::even) 
  113.     // Lambda 表达式能指定为参数 
  114.     val notZero = not {n -> n == 0} 
  115.     /* 
  116.     如果一个lambda仅有一个参数,它的声明可以被忽视(随着 ->一起). 
  117.     单个参数名将是"it". 
  118.     */ 
  119.     val notPositive = not {it > 0} 
  120.     for (i in 0..4) { 
  121.         println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") 
  122.     } 
  123.  
  124.     //  "class" 是用来声明类 
  125.     class ExampleClass(val x: Int) { 
  126.         fun memberFunction(y: Int): Int { 
  127.             return x + y 
  128.         } 
  129.  
  130.         infix fun infixMemberFunction(y: Int): Int { 
  131.             return x * y 
  132.         } 
  133.     } 
  134.     /* 
  135.     创建新的实例使用构造器 
  136.     Kotlin没有 "new"  
  137.     */ 
  138.     val fooExampleClass = ExampleClass(7) 
  139.     // 成员函数能使用点符号调用 
  140.     println(fooExampleClass.memberFunction(4)) // => 11 
  141.  
  142.     /* 
  143.     如果一个函数被"infix"标注,能使用infix notation调用 
  144.     下面fooExampleClass infixMemberFunction 4等同于 
  145. fooExampleClass.memberFunction(4) 
  146.     */ 
  147.     println(fooExampleClass infixMemberFunction 4) // => 28 
  148.  
  149.     /* 
  150.    数据类是创建只包含数据的精确方式. 
  151.      "hashCode"/"equals" 和 "toString" 等方法会自动产生。 
  152.     */ 
  153.     data class DataClassExample (val x: Int, val y: Int, val z: Int) 
  154.     val fooData = DataClassExample(1, 2, 4) 
  155.     println(fooData) // => DataClassExample(x=1, y=2, z=4) 
  156.  
  157.     // 数据类没有 "copy" 函数 
  158.     val fooCopy = fooData.copy(y = 100) 
  159.     println(fooCopy) // => DataClassExample(x=1, y=100, z=4) 
  160.  
  161.     // 对象能被解构入多个变量。 
  162.     val (a, b, c) = fooCopy 
  163.     println("$a $b $c") // => 1 100 4 
  164.  
  165.     // 解构 "for" 循环 
  166.     for ((a, b, c) in listOf(fooData)) { 
  167.         println("$a $b $c") // => 1 100 4 
  168.     } 
  169.  
  170.     val mapData = mapOf("a" to 1, "b" to 2) 
  171.     // Map.Entry 也能解构 
  172.     for ((key, value) in mapData) { 
  173.         println("$key -> $value") 
  174.     } 
  175.  
  176.     //  "with" 函数类似JavaScript "with" 语句. 
  177.     data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) 
  178.     val fooMutableData = MutableDataClassExample(7, 4, 9) 
  179.     with (fooMutableData) { 
  180.         x -= 2 
  181.         y += 2 
  182.         z-- 
  183.     } 
  184.     println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8) 
  185.  
  186.     /* 
  187.     使用 "listOf" 函数创建集合 
  188.     集合是不可变的,元素不能增加和移走 
  189.     */ 
  190.     val fooList = listOf("a", "b", "c") 
  191.     println(fooList.size) // => 3 
  192.     println(fooList.first()) // => a 
  193.     println(fooList.last()) // => c 
  194.     // list元素可通过索引访问。 
  195.     println(fooList[1]) // => b 
  196.  
  197.     // 一个可变的 list能使用 "mutableListOf" 函数创建 
  198.     val fooMutableList = mutableListOf("a", "b", "c") 
  199.     fooMutableList.add("d") 
  200.     println(fooMutableList.last()) // => d 
  201.     println(fooMutableList.size) // => 4 
  202.  
  203.     // 使用 "setOf"  创建set 
  204.     val fooSet = setOf("a", "b", "c") 
  205.     println(fooSet.contains("a")) // => true 
  206.     println(fooSet.contains("z")) // => false 
  207.  
  208.     // 使用 "mapOf" f创建map 
  209.     val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) 
  210.     // Map values can be accessed by their key. 
  211.     println(fooMap["a"]) // => 8 
  212.  
  213.      //待续 
  214. /* 
  215.     使用 "generateSequence" f函数创建序列号,它是懒赋值的集合,只有使用时才真正赋值。 
  216.     */ 
  217.     val fooSequence = generateSequence(1, { it + 1 }) 
  218.     val x = fooSequence.take(10).toList() 
  219.     println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
  220.  
  221.     // 产生 斐波纳契案例 
  222.     fun fibonacciSequence(): Sequence<Long> { 
  223.         var a = 0L 
  224.         var b = 1L 
  225.  
  226.         fun next(): Long { 
  227.             val result = a + b 
  228.             a = b 
  229.             b = result 
  230.             return a 
  231.         } 
  232.  
  233.         return generateSequence(::next) 
  234.     } 
  235.     val y = fibonacciSequence().take(10).toList() 
  236.     println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 
  237.  
  238.     // Kotlin提供colletion的高阶函数。 
  239.     val z = (1..9).map {it * 3} 
  240.                   .filter {it < 20} 
  241.                   .groupBy {it % 2 == 0} 
  242.                   .mapKeys {if (it.key) "even" else "odd"} 
  243.     println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} 
  244.  
  245.     // "for" 循环 
  246.     for (c in "hello") { 
  247.         println(c) 
  248.     } 
  249.  
  250.     // "while" 循环是和其他语言一样 
  251.     var ctr = 0 
  252.     while (ctr < 5) { 
  253.         println(ctr) 
  254.         ctr++ 
  255.     } 
  256.     do { 
  257.         println(ctr) 
  258.         ctr++ 
  259.     } while (ctr < 10) 
  260.  
  261.     /* 
  262.     "if" 能表达返回一个值的表达式 
  263.     */ 
  264.     val num = 5 
  265.     val message = if (num % 2 == 0) "even" else "odd" 
  266.     println("$num is $message") // => 5 is odd 
  267.  
  268.     // "when" 能作为"if-else if" 替换 
  269.     val i = 10 
  270.     when { 
  271.         i < 7 -> println("first block") 
  272.         fooString.startsWith("hello") -> println("second block") 
  273.         else -> println("else block") 
  274.     } 
  275.  
  276.     // "when" 能带一个参数 
  277.     when (i) { 
  278.         0, 21 -> println("0 or 21") 
  279.         in 1..20 -> println("in the range 1 to 20") 
  280.         else -> println("none of the above") 
  281.     } 
  282.  
  283.     // "when" 能用在返回一个值的函数can be used as a function that returns a value. 
  284.     var result = when (i) { 
  285.         0, 21 -> "0 or 21" 
  286.         in 1..20 -> "in the range 1 to 20" 
  287.         else -> "none of the above" 
  288.     } 
  289.     println(result) 
  290.  
  291.     /* 
  292.     使用"is" 操作符检查类型,如果一个对象传入类型检查,就无需再次明确casting 它了 
  293.     */ 
  294.     fun smartCastExample(x: Any) : Boolean { 
  295.         if (x is Boolean) { 
  296.             // x is automatically cast to Boolean 
  297.             return x 
  298.         } else if (x is Int) { 
  299.             // x is automatically cast to Int 
  300.             return x > 0 
  301.         } else if (x is String) { 
  302.             // x is automatically cast to String 
  303.             return x.isNotEmpty() 
  304.         } else { 
  305.             return false 
  306.         } 
  307.     } 
  308.     println(smartCastExample("Hello, world!")) // => true 
  309.     println(smartCastExample("")) // => false 
  310.     println(smartCastExample(5)) // => true 
  311.     println(smartCastExample(0)) // => false 
  312.     println(smartCastExample(true)) // => true 
  313.  
  314.     // Smartcast also works with when block 
  315.     fun smartCastWhenExample(x: Any) = when (x) { 
  316.         is Boolean -> x 
  317.         is Int -> x > 0 
  318.         is String -> x.isNotEmpty() 
  319.         else -> false 
  320.     } 
  321.  
  322.     /* 
  323.     Extensions是一个增加新函数到类的方式,类似 C# extension 方法 
  324.     */ 
  325.     fun String.remove(c: Char): String { 
  326.         return this.filter {it != c} 
  327.     } 
  328.     println("Hello, world!".remove('l')) // => Heo, word! 
  329.  
  330.     println(EnumExample.A) // => A 
  331.     println(ObjectExample.hello()) // => hello 
  332. } 
  333.  
  334. // Enum类似Java enum类型 
  335. enum class EnumExample { 
  336.     A, B, C 
  337. } 
  338.  
  339. /* 
  340. "object"能被用于创建单例对象,不能初始化它,但是能使用名称引向它。类似 Scala singleton objects. 
  341. */ 
  342. object ObjectExample { 
  343.     fun hello(): String { 
  344.         return "hello" 
  345.     } 
  346. } 
  347.  
  348. fun useObject() { 
  349.     ObjectExample.hello() 
  350.     val someRef: Any = ObjectExample // we use objects name just as is 
  351. } 


注:相关教程知识阅读请移步到kotlin教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表