// Add K2J-Compat dependency
dependencies {
implementation 'com.github.alexdochioiu:k2j-compat:1.0.1'
}
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
final String number = take("+44 77 1234 1234")
.let((it) -> "0" + it.substring(4)) // 077 1234 1234
.let((it) -> it.replaceAll(" ", "")) // 07712341234
.unwrap(); // unwraps the result to String
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
final String nullStr = null;
final String number = take(nullStr)
._let((it) -> it.replaceAll(" ", "")) // this code will not run as 'it' is null
.unwrap(); // returns null
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
StringBuilder builder = new StringBuilder();
take(builder).also((it) -> it.append("Hello World!"));
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
StringBuilder builder = null;
take(builder)._also((it) -> it.append("Hello World!"));
// Note: using 'also' instead of '_also' will cause a null pointer exception when trying to append
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
String phoneNumber = "889944";
Integer number = take(phoneNumber)
.takeIf((it) -> it.matches("[0-9]+"))
._let(Integer::parseInt)
.unwrap();
import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
String phoneNumber = null;
Integer number = take(phoneNumber)
._takeIf((it) -> it.matches("[0-9]+"))
._let(Integer::parseInt)
.unwrap();
Note: If you use int instead of Integer NPE will be thrown as java will try to unbox a null Integer to int
Similar to takeIf but with inverted logic
Similar to _takeIf but with inverted logic
- Unlike Kotlin, Java has primitive data types which get boxed/unboxed automatically into objects when needed. However, NPE is thrown when Java tries to unbox a null Object to a primitive data type. This cannot be solved so a custom lint will be created to add a warning when using primitives are used.