275
CHAPTER 10: Development
To define an extension, for any operator
from the table of type
Infix
, you write the following:
infix operator fun TheClass.
( ... ){ ... }
Here, the function arguments are the second and any subsequent operands, and
this
inside
the function body refers to the first operand. For operators not of type
Infix
, just omit the
infix
.
Defining operators for your own classes certainly is a good idea. Amending standard Java or
Kotlin library classes by operators might improve the readability of your code as well.
Named Arguments
By using named arguments as follows:
fun person(fName:String = "", lName:String = "",
age:Int=0) {
val p = Person().apply { ... }
return p
}
you can make more expressive calls like this:
val p = person(age = 27, lName = "Smith")
Using parameter names means you don’t have to care about argument order, and in many
cases you can avoid overloading constructors for various parameter combinations.
Scoping Functions
The scoping functions allow you to structure your code in a way that’s different from using
classes and methods. Consider, for example, the following code:
val person = Person()
person.lastName = "Smith"
person.firstName = "John"
person.birthDay = "2011-01-23"
val company = Company("ACME")
Table 10-2.
(
continued
)
Symbol
Dostları ilə paylaş: