K2J-Compat
Bringing some of the Kotlin goodness to java
Installation with Android Gradle
// Add K2J-Compat dependency
dependencies {
implementation 'com.github.alexdochioiu:k2j-compat:1.0.1'
}
Usage
.let{ }
as .let()
1. Kotlin's 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
?.let{ }
as ._let()
2. Kotlin's 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
.also{ }
as .also()
3. Kotlin's import static com.github.alexdochioiu.k2jcompat.K2JCompat.take;
StringBuilder builder = new StringBuilder();
take(builder).also((it) -> it.append("Hello World!"));
?.also{ }
as ._also()
4. Kotlin's 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
.takeIf{ }
as .takeIf()
5. Kotlin's 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();
?.takeIf{ }
as ._takeIf()
6. Kotlin's 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
.takeUnless{ }
as .takeUnless()
7. Kotlin's Similar to takeIf but with inverted logic
?.takeUnless{ }
as ._takeUnless()
8. Kotlin's Similar to _takeIf but with inverted logic
Known Limitations
- 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.