How to Set Default Clouse Param in View Method

How to set a default value as RangeInt when I use a ForEach method?

You need to use dynamic variant of ForEach, otherwise it will not be updated when data appeared

ForEach(appState.arrayInfos?.indices ?? 0..<0, id: \.self) { index in
VStack {
InfoRow(no: index, info: appState.arrayInfos![index])
}
}

Set default value of property of object passed on parameter to function

just check it and set it:

export const Map: FunctionComponent<MapProps> = function Map({
settings,
}) {
settings.rotation = (settings.rotation || settings.roation === 0) ? settings.rotation : 360

Default value for implicit parameter of class method

Without commenting on the wisdom of this (I think it depends), nothing prevents you from supplying default arguments on your implicit params. If you do this, a resolved implicit will take precedence, but if no implicit is found, the default argument will be used.

However, your withTx function won't work no matter what, because the implicit you define is not in the scope from the function block. (You could not have referred to tx from a function you define there.)

To modify your example (giving transactions a label to make this clear):

class Foo {
var m = scala.collection.mutable.HashMap.empty[String, String]

case class Tx(label : String, mcopy: scala.collection.mutable.HashMap[String, String]) {
def commit = (m = mcopy)
def rollback = () // not copying mcopy will lose all changes made to it
}

def withTx(block: Foo => Unit): Unit = {
implicit val tx = new Tx("oopsy", m.clone)
try {
block(this)
tx.commit
} catch {
case _: Throwable => tx.rollback
}
}

implicit val emptyTx = new Tx("passthrough", m) // non-tx operations will be performed directly on 'm'

def add(k: String, v: String)(implicit t: Tx = emptyTx): Unit = {
println( t )
t.mcopy += k -> v
}
}

Then...

scala> val f = new Foo
f: Foo = Foo@3e1f13d2

scala> f.add( "hi", "there" )
Tx(passthrough,Map())

scala> implicit val tx = new f.Tx( "outside", scala.collection.mutable.HashMap.empty )
tx: f.Tx = Tx(outside,Map())

scala> f.add( "bye", "now" )
Tx(outside,Map())

But your withTx(...) function doesn't do what you want, and now, unhelpfully, it doesn't call attention to the fact it doesn't to what you want with an error. It just does the wrong thing. Instead of getting the implicit value that is not in scope, the operation in block gets the default argument, which is the opposite of what you intend.

scala> f.withTx( foo => foo.add("bye", "now") )
Tx(passthrough,Map(bye -> now, hi -> there))

Update:

To get the kind of withTx method you want, you might try:

  def withTx(block: Tx => Unit): Unit = {
val tx = new Tx("hooray", m.clone)
try {
block(tx)
tx.commit
} catch {
case _: Throwable => tx.rollback
}
}

Users would need to mark the supplied transaction as implicit in their blocks. It would be something like this:

scala> val f = new Foo
f: Foo = Foo@41b76137

scala> :paste
// Entering paste mode (ctrl-D to finish)

f.withTx { implicit tx =>
f.add("boo","hoo")
tx.commit
}

// Exiting paste mode, now interpreting.

Tx(hooray,Map()) // remember, we print the transaction before adding to the map, just to verify the label

scala> println(f.m)
Map(boo -> hoo)

So that "worked". But actually, since you put an automatic commit in after the block completes, unless it completes with an exception, my call to tx.commit was unnecessary.

I don't think that's a great choice. Watch this:

scala> :paste
// Entering paste mode (ctrl-D to finish)

f.withTx { implicit tx =>
f.add("no","no")
tx.rollback
}

// Exiting paste mode, now interpreting.

Tx(hooray,Map(boo -> hoo)) // remember, we print the transaction before adding to the map, just to verify the label

scala> println(f.m)
Map(no -> no, boo -> hoo)

The add(...) completed despite my explicit call to rollback! That's because rollback is just a no-op and an automatic commit follows.

To actually see the rollback, you need to throw an Exception:

scala> :paste
// Entering paste mode (ctrl-D to finish)

f.withTx { implicit tx =>
f.add("really","no")
throw new Exception
}

// Exiting paste mode, now interpreting.

Tx(hooray,Map(no -> no, boo -> hoo)) // remember, we print the transaction before adding to the map, just to verify the label

scala> println(f.m)
Map(no -> no, boo -> hoo)

Now, finally, we can see a call to add(...) that was reverted.

Can swift closures be set to a default value when used as a parameter in a function?

Yes, functions are just values, so you can supply them as defaults

// just to show you can do it with inline closures or regular functions
func doNothing<T>(t: T) -> Void { }

func sendBody(
body: NSData? = nil,
success: (data: NSData) -> Void = { _ in return },
failure: (data: NSData?) -> Void = doNothing
)
{ }

Alternatively, you could make them optional, that way you can detect if the caller passed one:

func sendBody(
body: NSData? = nil,
success: ((NSData) -> Void)? = nil,
failure: ((NSData?) -> Void)? = nil
)
{ success?(NSData()) }

sendBody(success: { _ in print("ah, yeah!") })

Also worth noting if you’re doing this: if the caller uses the trailing closure syntax, this will be the last closure in the argument list. So you want the last one to be the one the user is most likely to want to supply, which is probably the success closure:

func sendBody(
body: NSData? = nil,
success: ((NSData) -> Void)? = nil,
failure: ((NSData?) -> Void)? = nil
)
{
if success != nil { print("passed a success closure") }
if failure != nil { print("passed a failure closure") }
}

// this prints "passed a failure closure"
sendBody { data in
print("which closure is this?")
}

Other than this, the order in the function declaration doesn’t matter to the caller – defaulted arguments can be supplied in any order.

ASP.NET MVC - passing parameters to the controller

Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}. If you left the routing as the default {controller}/{action}/{id} in your global.asax.cs file, then you will need to pass in id.

routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

... or something close to that.

Flutter default value for a Function

You can make them nullable fields as follows

  ReusableCard({required this.cardColor, this.cardChild, this.onPress});
final Color cardColor;
final Widget? cardChild;
final VoidCallback? onPress;

How do I use optional parameters in Java?

There are several ways to simulate optional parameters in Java:

  1. Method overloading.

    void foo(String a, Integer b) {
    //...
    }

    void foo(String a) {
    foo(a, 0); // here, 0 is a default value for b
    }

    foo("a", 2);
    foo("a");

One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.

  1. Varargs.

a) All optional parameters are of the same type:

    void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}

foo("a");
foo("a", 1, 2);

b) Types of optional parameters may be different:

    void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}

foo("a");
foo("a", 1);
foo("a", 1, "b2");

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.

  1. Nulls. To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:

    void foo(String a, Integer b, Integer c) {
    b = b != null ? b : 0;
    c = c != null ? c : 0;
    //...
    }

    foo("a", null, 2);

Now all arguments values must be provided, but the default ones may be null.

  1. Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:

    void foo(String a, Optional bOpt) {
    Integer b = bOpt.isPresent() ? bOpt.get() : 0;
    //...
    }

    foo("a", Optional.of(2));
    foo("a", Optional.absent());

    Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.

    Update: Java 8 includes the class java.util.Optional out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.

  2. Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:

    class Foo {
    private final String a;
    private final Integer b;

    Foo(String a, Integer b) {
    this.a = a;
    this.b = b;
    }

    //...
    }

    class FooBuilder {
    private String a = "";
    private Integer b = 0;

    FooBuilder setA(String a) {
    this.a = a;
    return this;
    }

    FooBuilder setB(Integer b) {
    this.b = b;
    return this;
    }

    Foo build() {
    return new Foo(a, b);
    }
    }

    Foo foo = new FooBuilder().setA("a").build();
  3. Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:

    void foo(Map<String, Object> parameters) {
    String a = "";
    Integer b = 0;
    if (parameters.containsKey("a")) {
    if (!(parameters.get("a") instanceof Integer)) {
    throw new IllegalArgumentException("...");
    }
    a = (Integer)parameters.get("a");
    }
    if (parameters.containsKey("b")) {
    //...
    }
    //...
    }

    foo(ImmutableMap.<String, Object>of(
    "a", "a",
    "b", 2,
    "d", "value"));

    In Java 9, this approach became easier:

    @SuppressWarnings("unchecked")
    static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {
    return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
    }

    void foo(Map<String, Object> parameters) {
    String a = getParm(parameters, "a", "");
    int b = getParm(parameters, "b", 0);
    // d = ...
    }

    foo(Map.of("a","a", "b",2, "d","value"));

Please note that you can combine any of these approaches to achieve a desirable result.



Related Topics



Leave a reply



Submit