kotlin function nesting

1. Local function nesting

Kotlin provides nesting of functions, and new functions can be defined inside functions.
This allows us to nest these advanced functions within functions to extract repetitive code.

class User(val id: Int, val name: String, val address: String, val email: String)
fun saveUser(user: User) {
 if (user.name.isEmpty()) {
 throw IllegalArgumentException("Can't save user ${user.id}: empty Name")
 }
  if (user.address.isEmpty()) {
 throw IllegalArgumentException("Can't save user ${user.id}: empty Address")
 }
 if (user.email.isEmpty()) {
 throw IllegalArgumentException("Can't save user ${user.id}: empty Email")
 }
 // save to db ...
}

The above code is actually very similar in judging whether the name, address, etc. are empty. At this time, we can
extract the same code together by declaring a general null function nested inside the function:

/** 利用局部函数抽取相同的逻辑,去除重复的代码* */
fun saveUser2(user: User) {
 fun validate(value: String, fildName: String) {
 if (value.isEmpty()) {
 throw IllegalArgumentException("Can't save user ${user.id}: empty
$fildName")
 }
 }
 validate(user.name, "Name")
 validate(user.address, "Address")
 validate(user.email, "Email")
}

2. Extended function nesting

In addition to using nested functions to extract, at this time, in fact, you can also use extended functions to extract, as shown below:
/** Use extended functions to extract logic * */

fun User.validateAll() {
 fun validate(value: String, fildName: String) {
 if (value.isEmpty()) {
 throw IllegalArgumentException("Can't save user $id: empty $fildName")
 }
 }
 validate(name, "Name")
 validate(address, "Address")
 validate(email, "Email")
}
fun saveUser3(user: User) {
 user.validateAll()
 // save to db ...
}

Guess you like

Origin blog.csdn.net/github_37610197/article/details/125547082