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,
secondOrNull
can be called on anyList<T>
instance, whereT
is a generic type representing the type of elements in the list. - Return Type: The function returns an element of type
T
if 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,
isEven
can be called on any instance ofInt
, like a method ofInt
itself. - Return Type: The function returns a
Boolean
value (true
orfalse
).
Implementation
this % 2 == 0
this
refers to the instance ofInt
on 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
email
attribute of aCustomer
object is in a valid format. - Extension Function: As an extension function,
isEmailValid
can be invoked on any instance ofCustomer
, treating it like a method ofCustomer
. - Return Type: It returns a
Boolean
value,true
if the email is valid, andfalse
otherwise.
Implementation
return email.contains("@") && email.contains(".")
- The function checks two conditions in the
email
string 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
Customer
object is valid based on specified criteria. - Extension Function: This function can be called on any instance of
Customer
as if it were a method inherent to theCustomer
class. - Return Type: The function returns a
Boolean
value:true
if the customer is considered valid,false
otherwise.
Implementation
return id != null && isEmailValid() // Add more conditions as needed
id != null
: Checks whether theid
property of theCustomer
is not null, implying that a validCustomer
should 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
true
only 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