Works fine var bar: String = "bonjour" bar = null // Compile-time error foo?.let { // `it` is the "unwrapped" value showMessage(it) } fun showMessage(message: String) { // I know for sure that `message` is not null, and will never change }
.flatMap { it.characteristics } .forEach { when (it.uuid) { NokeDefines.TX_CHAR_UUID -> txCharacteristic = it NokeDefines.RX_CHAR_UUID -> rxCharacteristic = it NokeDefines.STATE_CHAR_UUID -> stateCharacteristic = it } } At Liip, we are used to LINQ in C#, but Java on Android is not quite there yet.
int id; //... public static Bike fromApiModel(ApiBike model) { return new Bike(model.id); } } Kotlin data class Bike(val id: Int) { companion object { fun fromApiModel(model: ApiBike): Bike { return Bike(model.id) } } }
extends ServiceResponse { public T result; } public class Error extends ServiceResponse { public String errorMessage; } } void callback(ServiceResponse<String> response) { if (response instanceof ServiceResponse.Success) { ServiceResponse<String>.Success success = (ServiceResponse<String>.Success) response; String result = success.result; // result... } else if (response instanceof ServiceResponse.Error) { // ... } else { // OMG, What do I do now !? } }
T) : ServiceResponse<T>() data class Error<T>(val message: String) : ServiceResponse<T>() } fun callback(ServiceResponse<String> response) { when (response) { is Success -> { // `response` is automatically cast to the correct type. val token = response.data // String } is Error -> showError(response.message) // The compiler checks if all subclasses have been tested } } callback(ServiceResponse.Success("Yeah")) // `String` type is inferred
val age: Int) The compiler automatically derives the following members from all properties declared in the primary constructor: equals() / hashCode() pair toString() of the form "User(name=John, age=42)" copy() function
Kotlin Fully interoperable with Java IntelliJ is super helpful Paste Java code: it translates into Kotlin Helpers to make code more like Kotlin help a lot to learn