1. Extension for List<T>: List<T>.secondOrNull()
- Purpose: This function is designed to safely retrieve the second element of a list if it exists.
- Extension Function: As an extension function,
secondOrNullcan be called on anyList<T>instance, whereTis a generic type representing the type of elements in the list. - Return Type: The function returns an element of type
Tif the list has a second element, otherwisenull.
Implementation
fun <T> List<T>.secondOrNull(): T? = if (this.size >= 2) this[1] else null
- The function first checks if the size of the list is greater than or equal to 2 (
this.size >= 2). - If the list has two or more elements, it returns the second element (
this[1]). In Kotlin, list indices start at 0, so the second element is at index 1. - If the list has fewer than two elements, it returns
null.
Usage
override fun getSecondOrNullCustomer(): Customer? {
return generateCustomers().secondOrNull()
}
2. Extension for Int: Int.isEven
fun Int.isEven(): Boolean = this % 2 == 0
- Purpose: This function determines whether an integer (
Int) is even. - Extension Function: Being an extension function,
isEvencan be called on any instance ofInt, like a method ofIntitself. - Return Type: The function returns a
Booleanvalue (trueorfalse).
Implementation
this % 2 == 0
thisrefers to the instance ofInton which the function is called.- The expression performs a modulo operation (
%) to find the remainder when the integer is divided by 2. - If the remainder is 0 (
== 0), the number is even, so the function returnstrue. Otherwise, it returnsfalse.
Usage
override fun getCustomersByAgeIsEven(): List<Customer> {
return generateCustomers().filter { customer -> customer.age.isEven() }
}
3. Extension for Customer.isEmailValid
fun Customer.isEmailValid(): Boolean {
return email.contains("@") && email.contains(".")
}
- Purpose: To determine if the
emailattribute of aCustomerobject is in a valid format. - Extension Function: As an extension function,
isEmailValidcan be invoked on any instance ofCustomer, treating it like a method ofCustomer. - Return Type: It returns a
Booleanvalue,trueif the email is valid, andfalseotherwise.
Implementation
return email.contains("@") && email.contains(".")
- The function checks two conditions in the
emailstring of theCustomer:email.contains("@"): Checks if the email contains the “@” symbol, which is a standard part of an email address.email.contains("."): Checks if the email contains a period “.”, which is typically present in the domain part of an email address.
- Both conditions must be met (
&&) for the function to returntrue.
Usage
fun Customer.isValidCustomer(): Boolean {
return id != null && isEmailValid() // Add more conditions as needed
}
description:
4. Extension for Customer.isValidCustomer
fun Customer.isValidCustomer(): Boolean {
return id != null && isEmailValid() // Add more conditions as needed
}
- Purpose: To determine if a
Customerobject is valid based on specified criteria. - Extension Function: This function can be called on any instance of
Customeras if it were a method inherent to theCustomerclass. - Return Type: The function returns a
Booleanvalue:trueif the customer is considered valid,falseotherwise.
Implementation
return id != null && isEmailValid() // Add more conditions as needed
id != null: Checks whether theidproperty of theCustomeris not null, implying that a validCustomershould have an assigned identifier.isEmailValid(): Calls another extension function, presumably defined elsewhere, that checks if the customer’s email is in a valid format.- The function returns
trueonly if both conditions are satisfied (&&operator). - The comment “// Add more conditions as needed” suggests that the function is designed to be flexible and can be extended to include additional validity checks.
Usage
override fun saveCustomer(customerDto: CustomerDto): Customer {
//map to entity
val customer = customerDto.toEntity()
if(customer.isValidCustomer()) {
//for testing purpose log and return
logger.info("Customer $customer")
return customer
}else{
throw error("Invalid Email")
}
}
This text is another installment in the series of posts about Kotlin extensions.
Github: https://github.com/Kotlin-server-squad/articles


