Kotlin语言于Java的比较
1.变量
val(value的缩写):表示不可变量
var(variable的缩写):表示可变量
fun main(){
val a0=10
val a:Int=10
println("a="+a)
}
fun main(){
vara0=10
var a:Int=10
a=a*10
println("a"+a)
}
- Kotlin摒弃了Java中的基本数据类型,只有对象数据类型 对于final关键字,
- 在Java中需要著名,Kotlin是区分val和var
2.函数
fun methodName(param1:Int,param2:Int):Int{
reture 0
}
fun 定义函数关键字
methodName 方法名
param1:Int 参数名:数据类型
Int 返回的参数类型
简化形式
fun fun methodName(param1:Int,param2:Int):Int=max(num1,num2)
//只有一行代码可不用写函数体,返回参数类型等号链接,无需return
简化
fun methodName(param1:Int,param2:Int)=max(num1,num2)
//Kotlin可自行推导出返回函数为Int,可省略
3.逻辑语句
- if语句
fun largerNumber(num1:Int,num2:Int):Int{
var value=0
if(num1>num2){
value=num1
}else{
value=num2
}
return value
}
与Java区别
fun largerNumber(num1:Int,num2:Int):Int{
val value=if(num1>nnum2){
num1
}else{
num2
}
return value
}
-----------------------取消多余value变量----------------------------
fun largerNumber(num1:Int,num2:Int):Int{
return if(num1>nnum2){
num1
}else{
num2
}
}
------------------------等号替换---------------------------
fun largerNumber(num1:Int,num2:Int)=if(num1>num2){
num1
}else{
num2
}
--------------------------精简-------------------------
fun largerNumber(num1:Int,num2:Int)=if(num1>num2) num1 else num2
2.where语句
取消了Java中的switch中的break
fun getSCORE(name:String)=if(name=="Tom"){
86
}else if(name=="Jim"){
77
}else if(name=="Jack"){
95
}else if(name=="Lily"){
92
}else{
0
}
--------------------简写--------------------------
fun getSCORE(name:String)=when(name){
"Tom"->86
"Jim"->77
"Jack"->95
"Lily"->92
else->0
}
--------------------执行业务逻辑--------------------------
//is 关键字类似于Java中的instancer.内置了Int,Long,Float...
fun checkNumber(num:Number){
when(num){
is Int->println("number is Int")
is Double->println("number is Double")
else->println("number not support")
}
}
3.循环语句
区间[0,10]
val range=0..10
区间[0,10)
val range=0 utile 10
区间[0,10)等差数列d=2
for(i in 0 until 10 step 2){
println(i)
}
区间[10,1]
for(i in 10 downTo 1){
println(i)
}
4.面向对象编程
1.类与对象
摒弃了new关键字
package com.example.deom
class Person {
var name=""
var age=0
fun eat(){
print(name+"is eating.He is"+age+"year old.")
}
}
fun main(){
val p=Person()
p.name="Jack"
p.age=19
p.eat()
}
------------------------------
结果:Jackis eating.He is19year old.
2.继承与构造函数
继承
//关键字open允许被继承
open class Person {
var name=""
var age=0
fun eat(){
print(name+"is eating.He is"+age+"year old.")
}
}
---------------------------------------------------------------
//符号冒号 ":" 指代继承符号 ,此处括号不可省略
class Student : Person() {
var sno=""
var grade=0
}
主构造函数
open class Person{//无参构造函数
...
}
open class Person(val sno:String,val grade:Int){//有参构造函数
...
}
class Student(val sno:String,val grade:Int):Person(){//调取无参构造器
...
}
class Student(val sno:String,val grade:Int):Person(value sno:String, val grade:Int,name:String,age:Int):Person(name,age){//调取有参构造器 name与age不能声明为val,因为作用域,就会与父类同名
...
}
次构造函数
//当一个类既有主构造函数又有次构造函数时,所有次构造函数都必须调用主构造函数(包括间接调用)
class Student (val sno:String,val grade:Int,name:String,age:Int):Person(name,age){
constructor(name:String,age:Int):this("",0,name,age){
}
constructor():this("",0){
}
}
--------------------------------无主构造器--------------------------------
class Student:Person{
constructor(name:String,age:Int)super(name,age){
}
}
2.接口
Kotlin中的实现和继承都采用冒号":"作为关键字
interface Study {
fun readBooks()
fun doHomework(){
print("do homework default implementation")
}
}
open class Person(name:String,age:Int){
var name:String=""
var age:Int=0
}
class Student(name:String,age:Int):Person(name,age),Study{
override fun readBooks() {
println(name+"is reading.")
}
override fun doHomework(){
println(name+"is doing homework.")
}
}
fun main(){
val student=Student("Jack",19)
doStudy(student)
}
fun doStudy(study:Study){
study.readBooks()
study.doHomework()
}
3.修饰符
修饰符 | Java | Kotlin |
---|---|---|
public | 所有类可见 | 所有类可见(默认) |
private | 当前类可见 | 当前类可见 |
protected | 当前类,子类,统一包路径下的类可见 | 当前类,子类可见 |
default | 同一包路径下的类可见(默认) | 无 |
internal | 无 | 同一模块中的类可见 |
4.数据类与单例类(特有)
1.数据类
public class Cellphone{
String brand;
double price;
public Cellphone(String brand,double price){
this.brand=brand;
this.price=price;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Cellphone){
Cellphone other=(Cellphone)obj;
return other.brand.equals(brand)&&other.price==price;
}
return false
}
@Override
public int hashCode(){
return brand.hashCode()+(int)price;
}
@Override
public String toString(){
return "Cellphone(brand="+brand+",price="+price+")";
}
}
data关键字就如同于Java的注解一般的功能,内置了自动生成equals(),hashCode(),toString()等.
data class Cellphone (val brand:String,val price:Double){
}
fun main(){
val cellphone1=Cellphone("Samsung",1299.99)
val cellphone2=Cellphone("Samsung",1299.99)
print(cellphone1)
print(cellphone1==cellphone2)
}
2.单例
public class Singleton{
private static Singleton instance;
private Singleton(){}
public synchronized static Singleton getInstance(){
if(instance==null){
instance==new Singleton();
}
return instance;
}
public void singletonTest(){
System.out.println("singletonTest is called.")
}
}
Kotlin会在系统内自动创建一个实例
object Singleton {
fun singletonTest(){
println("singletonTest is called.")
}
}
5.Lambda编程
1.集合的创建与遍历
-----------------------------List--------------------------------------------------
val list=ArrayList<String>()
list.add("Apple")
list.add("Banana")
list.add("Orange")
----------静态集合--------------
val list=listOf("Apple","Banana","Orange")
for(fruit in list){
println(fruit)
----------动态集合-------------
val list=mutableeListOf("Apple","Banana","Orange")
list.add("Watermelon")
for(fruit in list){
println(fruit)
}
------------------------------Set-------------------------------------------------
----------静态集合--------------
val set=setOf("Apple","Banana","Orange")
for(fruit in set){
println(fruit)
----------动态集合-------------
val set=mutableeSetOf("Apple","Banana","Orange")
list.add("Watermelon")
for(fruit in set){
println(fruit)
}
--------------------------------Map--------------------------------------------------
val map=HashMap<String,Int>()
map.put("Apple",1)
map.put("Banana",2)
map.put("Orange",3)
--------------建议使用数组下标方式添加,获取----------------
val map=HashMap<String,Int>()
map["Apple"]=1
map["Banana"]-2
map["Orange"]=3
---------------------简化--------------------------------
val map=mapOf("Apple"to 1,"Banana"to 2,"Orange"to 3)
for((fruit,number)in map){
println("fruit is"+fruit+",number is"+number)
}
2.集合的函数式API
Lambda表达式语法结构
{参数名1:参数类型,参数名2:参数类型->函数体}
//获取最长的单词
val list=listOf("Apple","Banana","Orange")
val lambda={fruit:String->fruit.length}
val maxLengthFruit=list.maxBy(lambda)
-----------------删除多于变量简写--------------------
val maxLengthFruit=list.maxBy({fruit:String->fruit.length})
------------------简写--------------------
val maxLengthFruit=list.maxBy{fruit:String->fruit.length}
------------------简写--------------------
val maxLengthFruit=list.maxBy{fruit->fruit.length}
------------------简写--------------------
val maxlengthFruit=list.maxBy{it.length}
-------------------------其他API---------------------------------------------------
val newList=list.map{it.toUpperCase()} //转大写
val newList=list.filter{it.length<=5} //保留长度为5
val anyResult=list.any{it.length<=5} //判断集合中是否至少存在一个元素满足指定条件
val allResult=list.all{it.length<=5} //判断集合中是否所有元素都满足指定条件
6.1.空指针检查(2.可空类型系统,3.判断辅助工具)
1.Kotlin避免了空指针异常,它会将空指针检查提前到编译器,
2.如果想要让某个数据可以为空可在数据类型后加?
例如:fun doStudy(Study:Study?){...}
3.因为单独的?不能进行业务逻辑的判断处理,所以有了let函数的出现
例如:object.let{obj2->//编写具体的业务逻辑}
fun doStudy(study:Study?){
if(study!=null){
study.readBooks()
}
if(study!=null){
study.doHomework()
}
}
--------------------------------
fun doStudy(study:Study?){
study?.let{stu->
stu.readBooks()
stu.doHomework()
}
}
-----------只有一个参数,进行简化--------------------
fun doStudy(study:Study?){
study?.let{
it.readBooks()
it.doHomework()
}
}
7.其他
字符串内嵌表达式
"hello,${obj.name}.nice to meet you!"
函数的参数默认值
fun printParams(num:Int=21,str:String="hello"){
println("num is $num,str is $str")
}
fun main(){
printParams(str="hi",num=123)//采用键值对方式,不许用顺序要求
}
-------------------------------------------------
结果:num is 123,str is hI
应用实例
class Student(val sno:String,val grade:Int,name:String,age:Int):Person(name,age){
constructor(name:String,age:Int):this("",0,name,age){
}
constructor():this("",0){
}
}
-----------------------------------简化-------------------------------------
class Student(val sno:String="",val grade:Int=0,name:String="",age:Int=0):Person(name,age){
}
8.标准函数with,run,apply和静态方法
标准函数
-----------------一般--------------------------------
val List=listOf("Apple","Banana","Orange","Pear","Grape")
val bulilder=StringBuilder()
bulider.append("Start eating fruits.\n")
for(fruit in list){
bulider.append(fruit).append("\n")
}
bulider.append("Ate all fruits.")
val reasult=builder.toString()
println(result)
-----------------with格式-------------------------------
val result=with(obj){
//这里是obj的上下文
"value"//with函数的返回值
}
---修改为with-------
val List=listOf("Apple","Banana","Orange","Pear","Grape")
val result=with(StringBuilder()){
append("Start eating fruits.\n")
for(fruit in list){
append(fruit).append("\n")
toString()
}
println(result)
}
-------------------run的格式----------------------------
val result=obj.run{
//这里是obj的上下文
"value"//run函数的返回值
}
------修改为run格式----------
val list=listOf("Apple","Banana","Orange","Pear","Grape")
val result=StringBuilder().run{
append("Start eating fruits.\n")
for(fruit in list){
append(fruit).append("\n")
}
append("Ate all fruits.")
toString()
}
println(result)
-------------------apply的格式-------------------------
val result=obj.apply{//apply函数无法指定返回值,只能返回调用的对象本身
//这里是obj的上下文
}
//result==obj
--------修改为apply--------
val List=listOf("Apple","Banana","Orange","Pear","Grape")
val result=StringBuilder().apply{
append("Start eating fruits.\n")
for(fruit in list){
append(fruit).append("\n")
}
append("Ate all fruits.")
}
println(result.toString())
静态方法
Java中的静态方法添加static关键字.
Kotlin中
1.可以使用单例类和内部类方式来完成全部或部分的静态模拟,
2.或者使用@JvmStatic注解方式进行静态类,注解正能添加在单例类或者companion object方法上
3.采用顶层方法.Kotlin编译器会自动经所有的顶层方法全部编译成静态方法.通过创建.kt文件就行,在调用时可以直接使用,在Java中只能通过类名来进行调用.
calss Util{
fun doAction1(){
println("do action1")
}
companion object{
@JvmStatic
fun doAction2(){
println("do action2")
}
}
}