找了个学习大纲,从语法先开始吧,先了解下数据类型
大致有以下几种类型
Int, Short, Long, Float, Double, Byte, Char
相比java,首字母都大写了,其他区别不大
变量和类在使用过程中,省略了很多代码,感觉很舒服,测试demo如下,先写一部分,后面再添加
/**
* SDD:ADD FILE BY SHUCHNELIN ON 21/10/20
*/
class KotlinDataStructureTest : Activity(){
val TAG = "KotlinDataStructureTest"
//java里是boolean
var boolFlag:Boolean = true
//java int
var intFlag:Int = 1
//java short
var shortFlag:Short = 1
//jave long
var longFlag:Long = 1L
//java float
var floatFlag:Float = 1.0F
//java double
var doubleFlag:Double = 1.10
//java byte
var byteFlag:Byte = 1
//java char
var charFlag:Char = 'a'
//小写的char无法识别
//var litteCharFlag:char='a'
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
test()
}
fun test() {
//不会报错,可以相加,addDoubleAndInt输出2.1
val addDoubleAndInt = doubleFlag + intFlag
//会报错,提示不可与double相加
//val addDoubleAndInt2:Int = doubleFlag + intFlag
//java是通过+号连接变量,kotlin直接使用$
Log.d(TAG, "test addDoubleAndInt: $addDoubleAndInt")
}
//可定义一个无参空类
class Girl
//定义带两个参数的类
class Girl2(var character:String, var face:String, var sound:String)
class Girl3(var character:String, var face:String, var sound:String) {
init {
Log.d("KotlinDataStructureTest", "she is mine")
}
}
//这种有两个构造方法的类的写法不正确
// class Girl4 constructor(var character: String) constructor(var face: String, var sound: String)
//定义三个构造方法的类
class Girl4 constructor(var character: String) {
constructor(var face: String, var sound: String)
constructor(var sound: String, var height:String, var breast:String)
}
val myGirl:Girl = Girl()
//:Girl2可省略,Kotlin可自动获取后面的初始化参数类型
val myGirl2:Girl2 = Girl2("softy", "beauty", "sweet")
//初始化时即会自动运行init方法
val myGirl3 = Girl3("softy", "beauty", "sweet")
//分别用三个构造方法创建对象
val myGirl41 = Girl4("softy")
val myGirl42 = Girl4("beauty", "sweet")
val myGirl43 = Girl4("sweet", "165", "E")
}
|