写在前面的:
1,Kotlin学习之基础语法
2,Kotlin学习之类和继承
3,Kotlin学习之属性和字段
4,Kotlin学习之接口,可见性修饰符
去年6月份开始写了第一篇Kotlin基础语法的文章,但后来由于项目繁重,加上项目本身没有用到Kotlin,所以没有写下去,现在开始重头记录Kotlin学习历程!!!
1,定义函数
定义有两个Int参数,返回为Int的函数
fun sum(a : Int,b : Int) Int{
return a+b
}
fun main(args : Array<String>){
print("sum of a+b is")
println(sum(3,5))
}
结果:sum of a+b is 8
将表达式作为函数体,返回值类型自动推断的函数
fun sum(a : Int,b : Int) = a+b;
fun main(args : Array<String>){
println("sum of 5 and 6 is ${sum(5,6)}")
}
结果:sum of 5 and 6 is 11
函数无返回值
fun printSum(a : Int,b : Int) Unit {
println("sum of $a and $b is ${a + b}")
}
fun main(args : Array<String>){
printSum(-1,8)
}
结果:sum of -1 and 8 is 7
函数无返回值则Unit可省略
fun printSum(a : Int,b :Int){
println("sum of $a and $b is ${a + b}")
}
fun main(args : Array<String>){
println(-1,8)
}
结果:sum of -1 and 8 is 7
2,定义变量
a:定义常量
fun main(args : Array<String>){
val a : Int = 1 // 立即赋值
val b = 2 // 自动推断出 `Int` 类型
val c : Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
println("a=$a , b=$b , c=$c")
}
结果:a=1, b=2 , c=3
b:定义变量
var x= 5;
fun main(args : Array<String>){
x+=1;
println("x = $x")
}
结果:x = 6
3,使用字符串模板
fun main(args : Array<String>){
var a= 1
val s1= "a is $a"
a= 2
val s2="${s1.replace("is","was")},but now is $a"
println("s2")
}
结果:a was 1,but now is 2
4,条件表达式
fun maxOf(a : Int,b : Int) Int {
if(a>b){
return a
}else{
return b
}
}
也可以这样写:::
fun maxOf(a : Int,b : Int) = if(a > b) a else b
fun main(args : Array<String>){
println("maxOf 2 and 5 is ${maxOf(2,5)}")
}
结果:maxOf 2 and 5 is 5
5,空类型安全检测
当某个变量的值可以为 null 的时候,必须在声明处的类型后添加 ? 来标识该引用可为空。
fun parseInt(str : String) Int?{
return str.toIntOrNull()
}
fun printProduct(args1 : String,args2 : String){
var a= parseInt(args1)
var b= parseInt(args2)
if(a== null){
println("$a is not a number")
return
}
if(b== null){
println("$b is not a number")
return
}
// 在空检测后,a和 b 会自动转换为非空值
println(a * b)
}
fun main(args : Array<String>){
println("5","6")
println("x","55")
println("99","y")
}
结果:30
x is not a number
y is not a number
6,使用类型检测及自动类型转换
fun printStringLength(obj : Any) : Int?{
if(obj is String && obj.length>0){
return obj.length
}
return null
}
fun main(args : Array<String>){
fun printLength(obj : Any){
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
结果:
'Incomprehensibilities' string length is 21
'1000' string length is ... err, not a string
'[java.lang.Object@1be6f5c3]' string length is ... err, not a string
7,使用for循环语句
fun main(args: Array<String>) {
val items= listOf("apple","bear","banana")
for(item in items){
println(item)
}
}
结果:
apple
bear
banana
或者:
fun main(args: Array<String>) {
val items= listOf("apple","bear","banana")
for(item in items.indices){
println("item at $item is ${items[item]}")
}
结果:
item at 0 is apple
item at 1 is bear
item at 2 is banana
}
8,使用 while 循环
fun main(args: Array<String>) {
val items= listOf("apple","bear","banana")
var index= 0
while(index <items.size){
println("item at $item is ${items[item]}")
index++
}
结果:
item at 0 is apple
item at 1 is bear
item at 2 is banana
9,使用 when
表达式
fun describe(obj : Any) : String=
when (obj){
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
结果:
One
Greeting
Long
Not a string
Unknown
10, 使用区间(range)
a:使用 in 运算符来检测某个数字是否在指定区间内:
fun main(args : Array<String>){
val a= 10
val b= 9
if(a in 1.. b+1){
println("a in b")
}
}
结果:a in b
fun main(args : Array<String>){
val lists= listOf("a","b","c")
if(-1 !in 0.. lists.lastIndex){
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range too")
}
}
结果:
-1 is out of range
list size is out of valid list indices range too
b:区间迭代:
fun main(args : Array){
for (x in 1.. 5){
print(x)
}
}
结果:12345
c:数列迭代:
fun main(args: Array<String>) {
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
}
结果:
13579
9630
d:使用 in 运算符来判断集合内是否包含某实例:
fun main(args : Array<String>){
val items= listOf("apple", "banana", "kiwifruit")
when{
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}
结果:apple is fine too
11,使用 lambda 表达式来过滤(filter)和映射(map)集合:
fun main(args : Array<String>){
val list= listOf("banana", "avocado", "apple", "kiwifruit")
list
.filter{it.startWith("a")}//过滤以字母a开头的元素
.sortedBy{it}//对过滤后的元素进行排序
.map{it.toUpperCase()}//将拍完序的元素全部转换为大写字母
.forEach{println(it)}//打印元素
}
结果:
APPLE
AVOCADO
12,创建基本类及其实例(有待消化,暂时先挖坑):
fun main(args: Array<String>) {
val rectangle = Rectangle(5.0, 2.0) // 不需要“new”关键字
val triangle = Triangle(3.0, 4.0, 5.0)
println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rectangle.perimeter}")
println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${triangle.perimeter}")
}
abstract class Shape(val sides: List<Double>) {
val perimeter: Double get() = sides.sum()
abstract fun calculateArea(): Double
}
interface RectangleProperties {
val isSquare: Boolean
}
class Rectangle(
var height: Double,
var length: Double
) : Shape(listOf(height, length, height, length)), RectangleProperties {
override val isSquare: Boolean get() = length == height
override fun calculateArea(): Double = height * length
}
class Triangle(
var sideA: Double,
var sideB: Double,
var sideC: Double
) : Shape(listOf(sideA, sideB, sideC)) {
override fun calculateArea(): Double {
val s = perimeter / 2
return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC))
}
}
结果:
Area of rectangle is 10.0, its perimeter is 14.0
Area of triangle is 6.0, its perimeter is 12.0
网友评论