Kotlin入门到精通

官方中文学习文档

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","登录异常!")
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章