在kotlin中函数可以在类外部定义也可以在类内部定义,前者即为全局函数,后者,是类成员函数,语法一样
package loaderman.demo class Person { fun demo(name: String = "name", age: Int) { println(name + age) } }
package loaderman import loaderman.demo.Person fun main(arg: Array<String>) { var p = Person() p.demo(age = 9)//name 不赋值则使用默认值 }
可变参数用vararg关键字声明
package loaderman.demo class Persons (){ fun addPerson(vararg person: Person):List<Person>{ val arrayList = ArrayList<Person>() for (p in person) { arrayList.add(p) } return arrayList } }
package loaderman.demo class Person (name:String){ private var mName:String =name fun getName():String{ return mName } }
package loaderman import loaderman.demo.Person import loaderman.demo.Persons fun main(arg: Array<String>) { val addPerson = Persons().addPerson(Person("a"), Person("b")) for (addPerson in addPerson) { println(addPerson.getName()) } }
如果函数只有一行代码,那么可以直接在函数,如:
fun getName() String = mName