I have many confusion about Brackets in Dart(Flutter).
Which bracket "(), {}, []" is used for what?
() can group expressions:
var x = (1 + 2) * 3;
or can designate parameter lists for functions:
var getAnswer = () => 42;
int square(int x) => x * x;
or can designate function calls:
var answer = getAnswer();
var squared = square(4);
or is part of the syntax to some keywords. This includes (but is not limited to) if, assert, for, while, switch, catch:
if (condition) {
...
}
assert(condition);
for (var item in collection) {
...
}
while (condition) {
...
}
switch (value) {
...
}
try {
...
} on Exception catch (e) {
...
}
[] by itself creates List literals:
var list = [1, 2, 3];
var emptyList = []; // Creates a List<dynamic>.
or when used on an object, calls operator [], which usually accesses an element of a collection:
var element = list[index];
var value = map[key];
or in a parameter list, specifies optional positional parameters:
int function(int x, [int y, int z]) {
return x + y ?? 0 + z ?? 0;
}
function(1, 2);
or in dartdoc comments, creates linked references to other symbols:
/// Creates a [Bar] from a [Foo].
Bar fooToBar(Foo foo) {
// ...
}
{} can create a block of code, grouping lines together and limiting variable scope. This includes (but is not limited to) function bodies, class declarations, if-else blocks, try-catch blocks, for blocks, while blocks, switch blocks, etc.:
class Class {
int member;
}
void doNothing() {}
void function(bool condition) {
{
int x = 'Hello world!';
print(x);
}
if (condition) {
int x = 42; // No name collision due to separate scopes.
print(x);
}
}
or by itself can create Set or Map literals:
var set = {1, 2, 3};
var emptySet = <int>{};
var map = {'one': 1, 'two': 2, 'three': 3};
var emptyMap = {}; // Creates a Map<dynamic, dynamic>
or in a parameter list, specifies optional named parameters:
int function(int x, {int y, int z}) {
return x + y ?? 0 + z ?? 0;
}
function(1, y: 2);
or creates enumerations:
enum SomeEnumeration {
foo,
bar,
baz,
}
or in Strings is used to disambiguate interpolated expressions:
var foo = 'foo';
var foobar = '${foo}bar';
var s = '${function(1, 2)}';
<> when used as a pair in function or class declarations creates generics:
class GenericClass<T> {
T member;
}
T function<T>(T x) {
// ...
}
or specifies explicit types when using generics:
var map = <String, int>{};
Related
I’m trying to make my methods reactive to update the view in Compose. How to do it properly?
interface Foo{
val a: Int
fun bar(): Int
fun foo(): MutableStateFlow<Int> = MutableStateFlow(bar() * a)
}
//#Composable
val foo by fooImpl.foo().collectAsState()
P.S. Currently I made a hack: empty usage a variable a participated in calculations. But it’s not good.
val a = fooImpl.collectAsState()
a
One way to do it - subscribe to all variables used in a method.
var a = MutableStateFlow(0)
fun bar() = a.value +1
fun chad() = 42
fun foo() = bar() * chad()
val foo: Flow
get() = a.map { (it + 1) * chad() }
fun useFoo() = runBlocking {
withContext {
foo.collect {
something(it)
}
}
}
Consider this code:
type Foo =
{
X : int
Y : string
Z : int
}
module M =
let f foo =
let foo =
{
foo with
X = 123
}
let foo =
{
foo with
Y = "abc"
}
let foo =
{
foo with
X = foo.X + 1
}
foo
let g foo =
{
foo with
X = 123 + 1
Y = "abc"
}
Note that f and g do the same.
Using SharpLab, this is equivalent to:
// ...
[CompilationMapping(SourceConstructFlags.Module)]
public static class M
{
public static Foo f(Foo foo)
{
Foo foo2 = new Foo(123, foo.Y#, foo.Z#);
Foo foo3 = new Foo(123, "abc", foo2.Z#);
return new Foo(124, "abc", foo3.Z#);
}
public static Foo g(Foo foo)
{
return new Foo(124, "abc", foo.Z#);
}
}
// ...
Despite achieving the same thing, f allocates 3 times and g only once.
Is there a compiler flag or similar I can use to get f to compile more like g?
I'm almost certain what you're asking for doesn't exist and that every with involves a new copy. Adding the [<Struct>] attribute to your record might give you more performant allocation. See here for more details: https://bartoszsypytkowski.com/writing-high-performance-f-code/
I know that you can initialize final variables in a class with something like:
class A {
final num x;
final num y;
final num d;
A(this.x, this.y):
d = sqrt(pow(x, 2) + pow(y, 2));
}
And you can create regular variables inside a constructor like this:
class A {
String z;
A(){
z = 'hello';
}
}
But how do you mix both? Is it possible? What is the syntax?
Simply continue with the constructor right after the initializer, but, since you're going to use curly brackets ({}), you shouldn't use the semi-colon (;):
class A {
final num x;
final num y;
final num d;
String z;
A(this.x, this.y)
: d = sqrt(pow(x, 2) + pow(y, 2))
{
z = 'hello';
}
}
This function should transform each element of the list with the given function transform:
void _doSomething(List<Something> numbers, [transform(Something element)]) {...}
As I don't want to skip this method when the transform should not do anything, I wanted to give a default value to the transform method like this:
void _doSomething(List<Something> numbers,
[transform(Something element) = (v) => v]) {...}
Unfortunately, the editor tells me
Expected constant expected
Is there some workaround or simply not possible (or shouldn't be done like this at all)?
if you want to initialize a Function parameter that is also a field of your class I suggest:
class MyClass{
Function myFunc;
MyClass({this.myFunc = _myDefaultFunc}){...}
static _myDefaultFunc(){...}
}
Or more suitable:
typedef SpecialFunction = ReturnType Function(
FirstParameterType firstParameter,
SecondParameterType secondParameter);
class MyClass{
SpecialFunction myFunc;
MyClass({this.myFunc = _myDefaultFunc}){...}
static ReturnType _myDefaultFunc(FirstParameterType firstParameter,
SecondParameterType secondParameter){...}
}
You can define the default function as private method :
_defaultTransform(Something v) => v;
void _doSomething(List<Something> numbers,
[transform(Something element) = _defaultTransform]) {...}
Or check argument like this :
void _doSomething(List<Something> numbers, [transform(Something element)]) {
if (!?transform) transform = (v) => v;
...
}
Or like Ladicek suggests :
void _doSomething(List<Something> numbers, [transform(Something element)]) {
transform ??= (v) => v;
...
}
Write your default parameters inside a square bracket []
DummyFunctin(String var1, int Var2,[ String var3 = "hello", double var4 = 3.0, List<int> var5 = [2,4,5,6],] ){
// some calculation
// return something
}
this is example code in C# :
class exampleClass
{
struct exampleStruct
{
public int number;
}
private exampleStruct[,] e;
private enum exampleMove { Up, Down, Right, Left, Enter, Escape };
Stack<int> returnPath;
bool returntoBeg;
int numRandomMoves;
public exampleClass()
{
e = new exampleStruct[5, 5];
exampleStruct ex;
returntoBeg = false;
returnPath = new Stack<int>();
numRandomMoves = 0;
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
ex = new exampleStruct();
ex.number = 0
e[x, y] = ex;
}
}
}
}
I have an example code like above, i want to translate it into F#. But the problem is, when i make a class using F# and define struct in it, it shows errors and pointing that i can't declare type inside class type. Any help?
I think the following is a good workaround for nested types.
namespace MyNamespace
module private PrivateTypes =
[<Struct>]
type ExampleStruct(number: int) =
member __.Number = number
open PrivateTypes
type ExampleClass() =
let e = Array2D.init 5 5 (fun y x -> ExampleStruct(0))
//other members
ExampleStruct is nested under PrivateTypes, which is only visible in the same file.
While you cannot nest types, you can use intrinsic complex types that F# provides. Tuples are often a good data structure for data that has not very wide, observable scope, such as it is in your case.
In practice, I usually define implementation types in a module called e. g. Internal, and do not allow them to escape from the library. You may also define separate module per logical group of classes or even per complex class implementation.