Idioms
使用Data标识一个类为数据处理类。自带如下方法:
data class Customer(val name: String, val email: String)
fun main(args: Array<String>) {
val customer = Customer("doctorq","[email protected]")
println(customer.toString())
println(customer.equals("dd"))
println(customer.email)
println(customer.name)
println(customer.copy())
}
就是定义函数传参的时候附上初始值就行了
fun maxOf1(a: Int = 0, b: Int) = if (a > b) a else b
上面的函数如果a不传递值是,默认为0。
如果不传a的值,需要显式赋值给b
fun main(args: Array<String>) {
println(maxOf1(b=1))
println(maxOf1(3,2))
}
fun maxOf1(a: Int = 0, b: Int) = if (a > b) a else b
val list = listOf(1, 2, 3, 4, -1)
val listbyFilter = list.filter { x -> x > 0 }
println(listbyFilter)
简写如下:
val list = listOf(1, 2, 3, 4, -1)
val listbyFilter = list.filter {it > 0 }
println(listbyFilter)
val name = "doctorq"
println("Nams $name")
data class Customer(val name: String, val email: String)
fun typeCheck(customer:Customer){
when (customer) {
is Customer -> println("this is Foo")
else -> println("other")
}
}
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for((k,v) in map){
println("$k is $v")
}
如果想要获取必须使用map["key"]
,必须使用""
,''
无法识别,这点有点不合理:
包含100
for(i in 0..100)
不包含100
for(i in 0 util 100)
关键字lazy,第一次使用时才会初始化,而且只会初始化一次
val p: String by lazy {
val o = "helloworld"
o
}
用object定义的对象为单例模式
object Singleton {
val name = "doctorq"
}
fun main(args:Array<String>){
println(Singleton.name)
}
对于一些已有类的方法,觉得已有方法不好用,可以进行修改或者扩展
比如我想写一个扩展toString方法,返回的字符串前面全部加上我的名字
fun String.toDoctorq(): String {
return "Doctorq! " + toString()
}
fun main(args: Array) {
println("hello world".toDoctorq())
}
之前在用java操作一个文件对象时,需要先判断File对象是否存在,然后再操作,而kotlin中直接用
?
来直接判断,如果存在执行后面代码,不存在直接返回null
fun main(args:Array<String>){
val files = File("Test").listFiles()
println(files?.size)
}
但是返回null
这个关键字不够友好,也可以自定义返回值
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
println(result)
}
fun count():Int{
return 12
}
fun main(args:Array<String>){
test()
}
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
println(result)
}
class Turtle {
fun penDown(){
println("penDown")
}
fun penUp(){
println("penUp")
}
fun turn(degrees: Double){
println("degrees $degrees")
}
fun forward(pixels: Double){
println("forward $pixels")
}
}
fun main(args: Array) {
val myTurtle = Turtle()
with(myTurtle) {
//draw a 100 pix square
penDown()
for (i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
}
fun main(args:Array){
val stream = Files.newInputStream(Paths.get("/Users/doctorq/Documents/Developer/git-project/learningkotlin1/learningkotlin1.iml"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
}
fun main(args: Array<String>) {
val a: Boolean? = null
val b: Boolean? = false
val c: Boolean? = true
checkBoolean(a)
checkBoolean(b)
checkBoolean(c)
}
fun checkBoolean(b: Boolean?) {
if (b == true) {
println("$b")
} else {
println("`b` is false or null")
}
}
请关注我的微信公众号号,实时接收最新文章