赞
踩
fun showMessage(message: String?): Unit {
message?.let {
println(it)
}
}
fun showName(name: String, age: Int = 2) : Unit {
println("My name is $name, my age is $age years old")
}
fun doubleOf(number: Int): Int {
return number + number;
}
fun total(single: Double, count: Int, percent: Double) : Double = single * count * percent
类的成员函数, 并且参数个数为1, 调用形式比较特殊, 函数的名字需要像操作符一样放在类对象和参数的中间用空格分开: obj op arg
常用中缀函数 to, “age” to 18 结果为 Pair(“age”, 18)
infix fun Char.repeat(times: Int) = "${
this}".repeat(times)
/// 比如定义乘法操作符 *
/// 整数 * 字符串 => 重复(整数次)输入字符串的字符串
operator fun Int.times(message: String) = message.repeat(this)
/// 表示数量不定的同类型参数
/// 在运行期间, vararg 标记的参数会表现为数组, 如果需要在函数内部传递给另一个vararg 参数的函数, 需要用 * 来引用
fun multiPrint(vararg messages: String) {
for (i in messages) {
print(i)
print(if (i === messages.last()) "" else ", ")
}
}
/// 定义时必须初始化, 可以通过类型推断省略常量的类型标志
/// 常量定义后, 不可再修改常量的值, 否则编译报错
val n: Int = 100
val name = "God"
/// 变量同样在定义时必须给定初始值, 及时是可空/可选类型, 也要使用null进行初始化
var number: String? = null
var age: Int = 0
var message = "Hahahaha"
var myName = "oyoung"
/// myName = null // 不允许
var yourName: String? = "Big SB"
yourName = null
class One
class Two(val value: Int, var name: String)
fun classUsage() {
val one = One()
var two = Two(0, "O")
/// 3.3 访问类属性
println(two.value)
/// 3.4 修改类属性
two.name = "Fuck"
}
class Queue<E>(vararg items: E) {
private val children = items.toMutableList()
fun enqueue(item: E) = children.add(item)
fun dequeue(): E = children.removeAt(0)
fun size() = children.size
fun isEmpty() = children
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。