Kotlin之扩展函数
JavaScript中的函数概念与使用方法 #生活知识# #编程教程#
在介绍扩展函数之前,我们先简单介绍一下变量和属性:
变量变量通常可以改变的,常量是不可改变的.例如java中的final修饰的变量就是常量不可改变的.
在kotlin中我们用val和var来修饰,val修饰的变量是不可变变量,var修饰的变量是可变变量
在kotlin有时候不需要去指定变量的类型,在初始化的时候回自动推断出来,这样可以让代码更加清晰和简洁
val dog = Dog() // Dog 对象
val str = “string” // String
val age = 18 // Int
val actionBar = supportActionBar //ActionBar
但是有些情况下是需要指定类型的,例:
val context:Context = Activity
属性与Java中的字段是相同的,但是更加强大.我们通过一个例子来比较他们的不同之处
`java:
public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }123456789
在java中我们通过setter和getter函数来操作和访问属性
kotlin:
public class Person { var name: String = "" } val person = Person() person.name = "name" val name = person.name1234567
在使用的时候直接使用就可以了,属性会默认使用getter和setter,当然我们也可以修改代码:
public classs Person { var name: String = "" get() = field.toUpperCase() set(value){ field = "Name: $value" } }1234567
filed是kotlin的预留字段用来访问属性
如果属性是val修饰的,这是我们只可以访问,不可以修改;既只能调用getter而不能调用它的setter
public classs Person { var name: String = "" get() = field.toUpperCase() }1234
如果只是用来接收数据的,例如在android中,我们用来将json数据转成对象,从而展示在页面中,这时候最好使用val
data class City(val id: Long, val name: String, val coord: Coordinates, val country: String, val population: Int) data class Coordinates(val lon: Float, val lat: Float)12 扩展函数
扩展函数是指在一个类上增加一种新的行为,甚至我们没有这个类代码的访问权限.这是一个缺少有用函数的类上扩展的方法.在java中我们通常会实现很多带有static的工具类.kotlin中我们可以使用扩展函数来实现这些功能.
扩展函数并不是真正地修改了原来的类,它是以静态导入的方式来实现的。扩展函数可以被声明在任何文件中,因此我们可以把一系列有关的函数放在一个新建的文件里。
例如:
View类型的扩展函数:我们可以创建一个kotlin文件ViewExtensions.kt
val View.ctx: Context get() = context var TextView.textColor: Int get() = currentTextColor set(v) = setTextColor(v) fun View.slideExit() { if (translationY == 0f) this.animate().translationY(-height.toFloat()) } fun View.slideEnter() { if (translationY < 0f) this.animate().translationY(0f) } fun Context.setTextViewRightImg(textView: TextView, res: Int) { val drawable = ContextCompat.getDrawable(this, res) drawable?.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight) textView.setCompoundDrawables(null, null, drawable, null) } ...... // 调用 it.second.textColor = Color.RED toolbar.slideExit() else toolbar.slideEnter() ......
1234567891011121314151617181920212223242526网址:Kotlin之扩展函数 https://www.yuejiaxmz.com/news/view/163668
相关内容
Python函数机器学习Machine Learning:成本(cost) 函数,损失(loss)函数,目标(Objective)函数的区别和联系?
求解函数方程函数f:R→R,f((x
已知函数f(x)是R上的奇函数,且x>0,f(x)=1,试求函数y=f(X)的表达式
Excel中SUMIF函数如何使用
y=ln(1+x)的反函数怎么求
【教案】函数y=Asin(ωx+φ)教学设计
srand()以及rand()函数用法(zz)
若函数y=x³
Python数据分析:统计函数绘制简单图形