kotlin常用语法


package com.kotlin


fun main(arg:Array<String>){
	println("hello world");	
	println("""hello K
	ot
	lin
	""")
	println(sum(1,2));
	
	println(hello("Kotlin"))
	
	val arr = arrayOf("A","B","C");
	arg0(arr);
	forArgs(arr)
	
	println( leng("abc") )
	println( leng(123));

	println( length("abc") )
	println( length(123));
	
	cases("abc")
	cases(2)
	cases(1)
	
	sumInRanges(1,3)
	
	
	print("\nis in ranges ? ")
	var s=0;
	if (s in 1..99999)
		println("+");
	else if(s in -99999..-1)
		println("-")
	else
		println("0");
	
	
	println("\narr="+arr.toList())
	if("A" in arr)
		println("A in arr")
	else
		println("A not in arr")
	
	
	
	var s1="abcde"
	var s2="bc"
	print("\n"+s2+" in "+s1+" ? ")
	if(s2 in s1)
		println(true)
	else
		println(false)
}
fun arg0(args:Array<String>){
	println("First argument: ${args[0]}")
}

fun forArgs(args:Array<String>){
	
	for(a in args){
		println(a)
	}
	
	print("-----\n")
	
	for(i in args.indices)
		println(args[i])
}

fun hello(who:String):String="hello,"+who;

fun sum(a: Int, b: Int): Int {
	return a + b
}

fun length(s:Any):Int?{
	if(s is String)
		return s.length
	return null;
}

fun leng(s:Any):Int?=if(s is String) s.length else null;

fun cases(obj: Any) {
	print(obj)
    print(" --> ")
	when (obj) {
		"Hello"    -> print("Hello")
		is Int    -> print("Int")
		1          -> print("One") 
		!is String -> print("Not a string")
		else       -> print("Unknown")
	 }
	println()
}



fun sumInRanges( begin:Int, end:Int){
	var s=0;
	for(a in begin..end){
		s=s+a
	}
	println(""+begin+"+...+"+end+" = "+s);
	
}

	

打印如下:

hello world
hello K
	ot
	lin
	
3
hello,Kotlin
First argument: A
A
B
C
-----
A
B
C
3
null
3
null
abc --> Unknown
2 --> Int
1 --> Int
1+...+3 = 6

is in ranges ? 0

arr=[A, B, C]
A in arr

bc in abcde ? true


你可能感兴趣的:(Kotlin)