年前快速地过了一遍Kotlin语法。这回计划花上半年的时间,从代码细节上重新系统的梳理一遍Kotlin语言。当然,性价比最高的方式是通过Kotlin开发项目来学习。
val = 加了final的变量
val message = "Kotlin" // final String message = "Kotlin";
var count = 0
val msg: String = "Kotlin" //value
var count2: Int = 0 // variant
val p = Person("Kotlin")
p.name
/*
Q1 var与val什么区别?
val = 加了final变量
*/
val languageList = arrayListOf("Kotlin", "Java")
languageList.add("Go")
类比Java Web JSP里的EL表达式
println("message = " + message)
println("message = $message")
println("count = ${count}")
println("language list size = ${languageList.size}")
println("\$: ${count2}")
fun max(a: Int, b: Int): Int {
if (a > b) {
return a
}
return b
}
fun max2(a: Int, b: Int) = if (a > b) a else b
问题:表达式和语句有什么区别?
表达式有返回值,语句没有。表达式可以包含在语句或表达式里。语句与语句之间是并列的
Kotlin常见的表达式有:if,when,try{}catch
fun filter(a: Int) {
when (a) {
0 -> println("0")
1 -> println("1")
in 2..10 -> println("in 2..10")
!in 11..20 -> println("! in 11..20")
Integer.parseInt("21") -> println("21")
22, 23 -> println("22 , 23")
else -> println("else")
}
}
fun filter2(x: Any) {
when (x) {
is Int -> println("Int")
is String -> println("String")
is Person -> print("JavaPerson")
}
}
fun filter3(x: Any) =
when (x) {
is Int -> {
val a = 3
"Int"
}
is String -> {
val b = ""
"String"
}
else -> {
"else"
}
}
fun filter4(x: Any) =
when {
x is Int -> "Int"
x is String -> "String"
else -> "else"
}
}
for (i in 0..5) {
println("i : $i")
}
for(j in 0 until 5){
println("j : $j")
}
for(k in 5 downTo 0){
println("k : $k")
}
val languageList = arrayListOf("Kotlin", "Java", "Go")
for((index, value) in languageList.withIndex()){
println("index = $index, value = $value")
}
val languageMap = hashMapOf("j" to "Java", "k" to "Kotlin", "g" to "Go")
for((key, v) in languageMap){
println("$key : map value = $v")
}
背景知识:
Java异常继承自Throwable,分为两种
Java处理异常有两种方式:
先看下Java的例子
//非受检异常
private static void testRuntimeException() {
int i = Integer.parseInt("!");
}
//受检异常
private void testCheckedException() {
try {
FileInputStream fileInputStream = new FileInputStream("/temp");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void testCheckedException2() throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream("/temp");
}
从上面程序可知:Java强制要求开发人员处理受检异常.
常见的受检异常: Exception, FileNotFoundException, IOException, SQLException
常见的未检查异常: NullPointerException, ClassCastException, ArrayIndexsOutOfBoundsException, ArithmeticException, NumberFormatException
上述Kotlin下的代码如下:
fun testRuntimeException(){
val i = Integer.parseInt("!")
}
fun testCheckedException(){
val fis = FileInputStream("/temp")
throw IllegalArgumentException("")
}
可知:与Java不同,对受检异常,Kotlin不强制开发人员处理。
小结
对于异常,Kotlin与Java的不同之处如下:
fun readNumber(){
val a = try {
val c = ""
Integer.parseInt("!")
}catch (e: Exception){
e.printStackTrace()
0
}
println("a = $a")
}
enum class Season{
SPRING,
SUMMER,
AUTUMN,
WINTER
}
enum class Color(val r: Int, val g: Int, val b: Int){
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0,0,255);
fun rgb() = r * 255 * 255 + g * 255 + b
}
我们看下Java的
public class Rectangle {
private final int width;
private final int height;
private final boolean isSquare;
public Rectangle(int width, int height, boolean isSquare) {
this.width = width;
this.height = height;
this.isSquare = isSquare;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public boolean isSquare() {
return isSquare;
}
}
等效Kotlin实现
class Rectangle(val width: Int, val height: Int){
val isSquare get() = width == height
}
Java中,成员变量就是一个字段,访问成员变量通过setter或者getter方法,相当于变量的访问器。Kotlin把这个概念作为语言层面的支持了。kotlin中每个属性,如果是val变量就自带访问器get(),如果是var属性则自带get()和set()
因此Kotlin中,一个属性 = 字段 + 访问器;这是Kotlin对Java语言的进化。
该文是对Kotlin实战一书第二章知识点代码的梳理和总结,完整代码,已上传到GitHub上,KotlinInActionExample 传送门