Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Meet Kotlin — or why I will never go back to Java!

Meet Kotlin — or why I will never go back to Java!

Jonas Schmid

March 08, 2018
Tweet

More Decks by Jonas Schmid

Other Decks in Programming

Transcript

  1. – Meet Kotlin — or why I will never go

    back to Java! Jonas Schmid - Mobile Romandie Beer Lausanne, 08.03.2018
  2. Foreword It's just my experience I am used to Java

    for Android, not Java 9 I love trying new things Versus staying with "we know it works" tech It's very similar to Swift
  3. De ning variables val foo: String = "hello" val bar

    = "bonjour" // Type is inferred bar = "monde" // Compile-time error var baz = "hello" baz = "world"
  4. Optionals var foo: String? = "hello" foo = null //

    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 }
  5. Immutability + optionals Seems "simple" but is quite powerful For

    example, all dependencies injected in an object are guaranteed to exist at any time No more if(foo != null) {
  6. De ning a function fun sum(a: Int, b: Int): Int

    { return a + b } or fun sum(a: Int, b: Int) = a + b
  7. Classes class Foo( private val myString: String, var myInt: Int

    ) { val bar = "myValue" } val foo = Foo("Hello", 42) foo.myInt = 4 foo.myString // Error foo.bar // "myValue"
  8. No more getters and setters Java class Foo { private

    String bar = "Yeah"; public String getBar() { return bar; } public void setBar(String value) { bar = value; } } Kotlin val foo = Foo() foo.bar // "Yeah" foo.bar = "Awesome"
  9. Kotlin can still have getters/setters var isLoggedIn: Boolean = false

    set(value) { field = value saveIsLoggedIn(value) }
  10. View visibility var View.isVisible: Boolean get() = this.visibility == View.VISIBLE

    set(value) { this.visibility = if (value) View.VISIBLE else View.GONE } myView.isVisible = false
  11. Functional helpers val numbers = listOf(4, 8, 15, 16, 23,

    42) val strings = numbers .filter { it % 2 != 0 } .map { if (it < 20) { return@map "It's below: $it" } else { return@map "It's above: $it" } } print(strings) // [It's below: 15, It's above: 23]
  12. Even simpler val numbers = listOf(4, 8, 15, 16, 23,

    42) val strings = numbers .filter { it % 2 != 0 } .map { return@map when { it < 20 -> "It's below: $it" else -> "It's above: $it" } }
  13. Real life example services .filter { it.uuid == NokeDefines.SCAN_SERVICE_UUID }

    .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.
  14. Simpler constructors Java class Foo { private String bar =

    "Yeah"; public Foo(String bar) { this.bar = bar; } public String getBar() { return bar; } public void setBar(String value) {bar = value; } } Kotlin class Foo(bar: String = "Yeah")
  15. No static methods in Kotlin Java class Bike { public

    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) } } }
  16. Like this ? class ServiceResponse<T> { public T result; public

    String errorMessage; } void callback(ServiceResponse<String> response) { if (response.result != null) { // response.result... } else if (response.errorMessage != null) { // response.errorMessage... } else { // OMG, What do I do now !? } }
  17. Or like that ? class ServiceResponse<T> { public class Success

    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 !? } }
  18. 8

  19. 9

  20. Sealed classes sealed class ServiceResponse<T> { data class Success<T>(val data:

    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
  21. Data classes From the doc: data class User(val name: String,

    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
  22. Callbacks Given the service with a callback: class AsyncService {

    fun callMeBack(callback: (String) -> Unit) { Thread.sleep(2000) callback("Yeah") } }
  23. Callbacks in Java void asyncUsage() { asyncService.callMeBack(new Function1<String, Unit>() {

    @Override public Unit invoke(String s) { System.out.print(s); return null; } }); }
  24. Lambdas on Android Java textview.setOnClickListener(new View.OnClickListener() { @Override public void

    onClick(View v) { doAction(); } }); Kotlin textview.setOnClickListener { doAction() }
  25. Pros Way less boilerplate code Modern mechanisms Immutability Functional programming

    No more ; It really looks like Swift - Easy switching between the two
  26. Pros Fully endorsed by Google New code samples are in

    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
  27. Cons One new language to learn? A few Java libs

    are incompatible Mockito, because of the re ection and type safety But there are alternatives! Help me nd one please!