//String类型,自动判断类型(不可变变量Value)val laugh = "lalalalala"//浮点类型,默认Doubleval PI = 3.1415//Float类型val PI_FLOAT = 3.1415F
//一旦赋值后不能改变,但是可以条件赋值val msg: Int = min(2,1)
//可变类型(Variable)
var status = 0fun block(){
//但类型不能改变,以下语句报错//status = "aaa"
}
函数
//参数和返回值都是写在: 后面
fun max(a: Int, b: Int): Int {
//if...else可代替?:returnif (a > b) aelse b
}
//函数也不用写在里面
//短函数块,还是能用=
fun min(a: Int, b: Int): Int = if (a > b) b elsea
类的定义
/**
class Test(val name: String = "Test")
==>等价于
publicclass Person{
private final String name;
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
}
//val只有getter方法//var有getter和setter方法
*/
//这是个默认构造器,并且可以赋个默认值class Test(val name: String = "Test") {
//参数和返回值都是写在: 后面fun max(a: Int, b: Int): Int {
//if...else可代替?:returnif (a > b) a else b
}
}
class Rectangle(val height: Int, val width: Int){
//自定义getter方法val isSquare: Boolean
get() = height == width
}
fun createRec(): Rectangle{
val random = Random()
return Rectangle(random.nextInt(),random.nextInt())
}
main函数和模板字符串
//main函数已经不能写在Class里面了
fun main(args: Array<String>) {
val max= Test().max(1,2) //和Java类似//字符串模板
println("The max is $max")
println("The min is ${min(1,2)}")
println(max is Int) //类似于instanceof
}
继承和接口
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
fun eval(e: Expr): Int{
if (e is Num){
//此处不用显性类型转化val n = e //as Numreturn n.value
}
if (e is Sum){
//在e is Sum为True时,该作用域内自动转化return eval(e.left) + eval(e.right)
}
throw IllegalArgumentException()
}
fun eval2(e: Expr): Int =
when (e){
is Num -> {
println("num: ${e.value}")
e.value
}
is Sum -> {
val left = eval2(e.left)
val right = eval2(e.right)
println("sum: $left + $right")
left + right
}
else -> throw IllegalArgumentException()
}
fun main(args: Array<String>){
val a = eval2(Sum(Sum(Num(1),Num(2)),Num(4)))
println(a)
}
Enum和when
//枚举类
enumclassColor (
val r: Int,
val g: Int,
val b: Int
){
RED(255,0,0),
ORANGE(255,165,0),
GREEN(0,255,0),
YELLOW(0,0,255),
BLUE(0,0,255),
JAOSDHO(161,18,25);
fun rgb() = (r * 256 + g) * 256 + b
//when来代替switch
fun getMnemonic(color: Color) =
when (color){
BLUE ->"Blue"
GREEN ->"Green"
ORANGE,RED ->"Red or Orange"else ->"fuck color"
}
fun mixColor(c1: Color, c2: Color) =
when (setOf<Color>(c1, c2)){
setOf(RED,YELLOW) -> ORANGE
setOf(YELLOW,BLUE) -> GREEN
else ->throw Exception("Unknown Color")
}
fun maxColor2(c1: Color, c2: Color): Color{
when{
(c1 == RED && c2 == YELLOW) ||
(c1 == YELLOW && c2 == RED) ->return ORANGE
else ->throw Exception("Unknown Color")
}
}
}
迭代和in
可以使用传统的while(){…}或do{…}while()
fun main(args: Array<String>){
//class kotlin.ranges.IntRangeval oneToTen = 1..10//包括10val oneToSize = 1 until 10//不包括10val tenToOne = 10 downTo 1//包括1val stepTwo = 1..10 step 2//1,3,5,7,9//class kotlin.ranges.CharRangeval charIter = 'A'..'F'
//test IntRangefor (i in stepTwo){
//println(i)
}
//Map上的迭代val sortedMap = TreeMap<Char,String>()
//test Mapfor (c in'A'..'F'){
//可以以Python的方式访问和赋值
sortedMap[c] = Integer.toBinaryString(c.toInt())
}
for ((k,v) in sortedMap){
println("$k = $v")
}
//List上的迭代val list = arrayListOf("10","11","1001")
for ((index,ele) in list.withIndex()){
println("$index : $ele")
}
//使用in来判断,使用的是Comparable接口的cfun isLetter(c: Char) = c in'a'..'z' || c in'A'..'Z'
fun isNotDigit(c: Char) = c !in '0'..'9'
println("KCK"in"J".."L") //true,K在J,L中间
println("Kotlin"in setOf("Java","Scala")) //false
}
try…catch…finally
可以和Java一样的用法
或作为表达式
fun readNumber(read: BufferedReader){
//try{}作为表达式
val number = try {
Integer.parseInt(readLine())
}catch (e: NumberFormatException){
return
}
}