官方中文學習文檔
https://www.kotlincn.net/docs/reference/classes.html
1.字段定義
val a: Int = 1
val b = 1 // 系統自動推斷變量類型爲Int
val c: Int // 如果不在聲明時初始化則必須提供變量類型
c = 1 // 明確賦值
var x = 5 // 系統自動推斷變量類型爲Int
x += 1 // 變量可修改
2.循環及遍歷
//只讀集合
val listOf = listOf<String>("呵呵1", "呵呵2", "呵呵3", "呵呵4")
for (s in listOf) {
print(s)
}
//可變集合
val mutableListOf = mutableListOf<String>()
mutableListOf.add("呵呵1")
mutableListOf.add("呵呵2")
mutableListOf.add("呵呵3")
mutableListOf.add("呵呵4")
mutableListOf.forEach(){
println(it)
}
//迭代器遍歷
val iterator = mutableListOf.iterator()
while (iterator.hasNext()){
println(iterator.next())
}
3.判斷
when(變量){
分支A -> 表達式
else -> 表達式
}
參考網址:
https://www.jianshu.com/p/b8eb0fe28dad
4.類的擴展方法
首先我們定義定義一個類
class Tool(){
fun say(str:String){
println("工具:${str}")//這是類特有的方法
}
}
然後我們給這個類寫一個擴展的方法
fun Tool.talk(str:String){
println("工具:${str}")
}
那麼我們在主函數運行一下
fun main(){
println(Tool().say("我是類特有的方法"))
println(Tool().talk("我是擴展的方法"))
}
最後的執行效果
5.接口的使用
首先我們定義一個接口
interface DataCallBack{
fun show(str:String);
}
(1)方法一:我們寫一個接口的實現類
class Realize():DataCallBack{
override fun show(str:String){
println("接口:調用了實現類的接口方法")
}
}
(2)方法二:我們定義一個這個接口的變量
var call1:DataCallBack = object:DataCallBack{
override fun show(str:String){
println("接口:${str}")
}
}
6. lambda 表達式
主要格式爲:
{參數列表->方法}
var lambda{a:Int,b:Int->printf("結果爲:${a+b}")}
7.高階函數
高階函數是將函數用作參數或返回值的函數。
fun <T, R> Collection<T>.fold(
initial: R,
combine: (acc: R, nextElement: T) -> R
): R {
var accumulator: R = initial
for (element: T in this) {
accumulator = combine(accumulator, element)
}
return accumulator
}
8.set()&get()字段
fun main(){
var s=S5()
println(s.str)//調用字段查看效果
s.str="字段f"//給字段賦值查看效果
println(s.str)//調用賦值後查看效果
}
//我們定義一個類測試 字段f代表賦值,字段c代表初始化值
class S5(){
var str: String="字段c"
get() = field+"獲得了"
set (value) {
field=value+"設置了"
}
}
主要效果:
9.代理模式
//主函數使用
fun main(){
//使用代理類,執行操作類中的方法
Dev(BaseIm("代理")).show();
}
//事件模型
interface Base{
fun show()
}
//操作類
class BaseIm(str:String):Base{
var str: String?=null
init{
this.str=str
}
override fun show(){
print(this.str)
}
}
//代理類
class Dev(b:Base):Base by b
其他
參考網址:
https://www.jianshu.com/p/35f0c16242e4
Kotlin 隨便練習的代碼
class Mapp : Application() {
override fun onCreate() {
super.onCreate()
NIMClient.init(this, getLoginInfo(),options())
}
private fun options():SDKOptions {
var options:SDKOptions =SDKOptions()
var config:StatusBarNotificationConfig =StatusBarNotificationConfig()
config.notificationSmallIconId = R.drawable.btn_default_small
config.ledARGB = Color.GREEN;
config.ledOnMs = 1000;
config.ledOffMs = 1500;
config.notificationSound = "android.resource://com.netease.nim.demo/raw/msg";
options.statusBarNotificationConfig = config;
config.notificationEntrance = null // 點擊通知欄跳轉到該Activity
config.notificationSmallIconId = R.drawable.btn_default_small
options.userInfoProvider = Uip()
return options;
}
private fun getLoginInfo():LoginInfo?{
return null
}
class Uip:UserInfoProvider{
override fun getDisplayNameForMessageNotifier(
account: String?,
sessionId: String?,
sessionType: SessionTypeEnum?
): String? {
return null
}
override fun getAvatarForMessageNotifier(sessionType: SessionTypeEnum?, sessionId: String?): Bitmap? {
return null
}
override fun getUserInfo(account: String?): UserInfo? {
return null
}
}
}
class MainActivity : AppCompatActivity(){
val arrayOf = arrayOf("張三", "李四", "王五")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var list:ListView=this.findViewById(R.id.list)
var adpter:ArrayAdapter<String> =ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,arrayOf)
list.adapter=adpter
dologin(LoginInfo("123","123456"))
}
fun dologin(info:LoginInfo){
NIMClient.getService(AuthService::class.java).login(info)
.setCallback(CallBack())
}
}
class CallBack:RequestCallback<LoginInfo>{
override fun onException(exception: Throwable?) {
Log.d("ssss","登錄成功!")
}
override fun onFailed(code: Int) {
Log.d("ssss","登錄失敗!")
}
override fun onSuccess(param: LoginInfo?) {
Log.d("ssss","登錄異常!")
}
}