Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Dart's equivalent to Kotlin's let?

Recently I've been delving into Flutter's ecosystem and Dart has proven itself a neat and simple language.

Currently, I am looking for a best practice to run methods if an optional variable is not null.

In other words, I am looking for something in Dart that is like Kotlin's let operator :

variable?.let {
    doStuff();
    doABitMoreStuff();
    logStuff();
}

Anyone got any ideas or best practices around this?

I've looked into Dart's documentation and have found nothing that would fit my requirements.

King regards,

like image 369
Ricardo Vieira Avatar asked Sep 03 '18 10:09

Ricardo Vieira


3 Answers

With the new Dart extension functions, we can define:

extension ObjectExt<T> on T {
  R let<R>(R Function(T that) op) => op(this);
}

This will allow to write x.let(f) instead of f(x).

like image 117
user3612643 Avatar answered Oct 30 '22 14:10

user3612643


Dart's equivalent would be a null-aware cascade operator: The Dart approach would be a to use a null-aware cascade:

SomeType? variable = ...

variable
   ?..doStuff()
    ..doABitMoreStuff()
    ..logStuff();

The null-aware cascade works like the normal cascade, except that if the receiver value is null, it does nothing.


You could make your own using a static function though:

typedef T LetCallback<T>(T value);

T let<T>(T value, LetCallback<T> cb) {
  if (value != null) {
    return cb(value);
  }
}

Then used like that:

let<MyClass>(foo, (it) {

})
like image 9
Rémi Rousselet Avatar answered Oct 30 '22 13:10

Rémi Rousselet


We can do it with Dart 2.6 or later.

extension ScopeFunctionsForObject<T extends Object> on T {
  ReturnType let<ReturnType>(ReturnType operation_for(T self)) {
    return operation_for(this);
  }
}

usage: https://github.com/YusukeIwaki/dart-kotlin_flavor#let

like image 4
YusukeIwaki Avatar answered Oct 30 '22 15:10

YusukeIwaki