class Employee(name: String,age:Int,college:String?,var company:String):Student(name,age,college){
override fun isEligibleToVote():Boolean{
return true
}
fun Person.isTeenager():Boolean{
return age in 13..19
}
fun isOctogenarian(): Boolean = age in 13..19
val sumLambda: (Int,Int)->Int = {x,y -> x+y}
fun doubleTheResult(x: Int, y: Int, f:(Int,Int)-> Int): Int{
return f(x,y)*2
}
fun Test(){
var result: Int = doubleTheResult(4,5,sumLambda)
var r1 = 1..5
var r2 = 1 downTo 5
//如果步长不是1,则需要使用step函数,例如:
var r3 = 1 downTo 5 step 2 //5 3 1
var age = 12;
var isEligibleToVote = if(age>11) "yes" else "no"
var typeOfPerson = when(age){
0 -> "New born"
in 1..12 -> "Child"
in 13..19 -> "Teenager"
else -> "Adult"
}
//遍历一个String对象数组
val names = arrayOf("Jake", "Jill", "Ashley", "Bill")
for(name in names){
println(name)
}
//Kotlin允许在字符串中嵌入变量和表达式,例如:
val name = "Bob"
println("My name is $name")
var a = 100
var b = 200
println("The sum is ${a+b}")
}
创建 Javabean 对象 关键字:data
data class Customer(val name: String, val email: String)
包含以下所有的属性:
- getters (and setters in case of vars) for all properties
- equals()
- hashCode()
- toString()
- copy()
- component1(), component2(), …, for all properties (see Data classes)
过滤list集合
val positives = list.filter { x -> x > 0 }
or
val positives = list.filter { it > 0 }
字符串拼接:
println("Name $name")
and
println("Name ${a+b}")
Instance Checks
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
Traversing a map/list of pairs
for ((k, v) in map) {
println("$k -> $v")
}
Using ranges
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
Read-only list
val list = listOf("a", "b", "c")
Read-only map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
Accessing a map
println(map["key"])
map["key"] = value
Creating a singleton:object
object Resource {
val name = "Name"
}
If not null shorthand
val files = File("Test").listFiles()
println(files?.size)
If not null and else shorthand
val files = File("Test").listFiles()
println(files?.size ?: "empty")
Executing a statement if null
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
Execute if not null
val data = ...
data?.let {
... // execute this block if not null
}
Return on when statement
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
'try/catch' expression
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
'if' expression
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
Calling multiple methods on an object instance ('with')
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
Java 7's try with resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}