If first param is true, then must pass second param in function - kotlin

I have my custom Kotlin's function:
fun getActiveCartTest(isAsync: Boolean = false, vararg callback: Callback<Cart> ): TransportResponse? {
...
}
It has one default param (isAsync) and one optional (vararg) callback param.
I can call this function from java like this:
1. TransportResponse transportResponse = TransportService.INSTANCE.getActiveCartTest();
2. TransportResponse transportResponse = TransportService.INSTANCE.getActiveCartTest(false);
3. TransportResponse transportResponse = TransportService.INSTANCE.getActiveCartTest(true);
4. TransportService.INSTANCE.getActiveCartTest(true, new DefaultRestClientCallback<Cart>() {
#Override
public void onTransportResponse(#NotNull TransportResponse transportResponse) {
}
});
Nice, it works.
But, when I use this call:
TransportResponse transportResponse = TransportService.INSTANCE.getActiveCartTest(true);
I get a compile error.
What I mean. When client wants to call async call of function getActiveCartTest then it MUST use two params: isAsync AND callback.
As you can see in my function getActiveCartTest the client can omit second param (callback). It's not correct.
I need if first param isAsync = true, then user also must pass second param callback. And if first param isAsync = false then user can omit second param (callback)
Is it possible in Kotlin?

Instead of trying to make code that nobody will be able to understand, why not divide your function in getActiveCartTestSync and getActiveCartTestAsync. The thing you want might be achievable by using reflection, however you make the code much more complicated without any reason.

Related

Lodash way of creating a custom function

I'm trying to implement a simple function in pure lodash way.
function forward(i) => {
return (j) => {
return String.fromCharCode(i + j)
}
}
So that I can do _.range(26).map(forward(65)). Take me some time to make this work:
function a = _.wrap(String.fromCharCode, (fn, a, b) => fn(a + b))
function b = _.ary(a, 2)
function forward = _.curry(b)
Now my question is is there an easier way to do this? and how do I use sum to construct (fn, a, b) => fn(a + b)?
One last thing is I couldn't find wrap function file in Lodash repo.
The function _.curry(...) is kind of strange when it comes to calling functions with various parameters. Let me guide you with an example below.
The ary-function (_.ary(..., 2)) takes any function and ensures its never called with more than a specific amount of arguments (in this case two). Less arguments than specified, will just end up calling the underlying function with less arguments. A definition of this function could look like this:
function ary() {
const args = arguments;
// implementation
}
There is no way to tell how many arguments the function is expecting, as you would with a function with actual parameters (function(a, b) { }). If you would define const forward1 = _.curry(_.ary(target, 2)), and call it with forward1(42)(2), the curry function would just pass down the first argument to ary as it thinks its done.
We can get around this by using an overload of curry that specifies how many parameters the underlying function is expecting (const forward2 = _.curry(target, 2)). Only in the case where forward2 is called in a curry-style (not sure what its even called) with two parameters, it passes it down to target. A call with one argument will just return a new function, waiting for it to be called with the second argument. Now we can get rid of the ary-call, as it serves us no purpose anymore.
As for chaining actions, there's a helper for that. For example: c(b(a(...) can be rewritten to _.flow([a, b, c]). Lodash also provides a function for a + b, which is _.add().
Together your problem can be rewritten to:
const forward = _.curry(_.flow([_.add, String.fromCharCode]), 2);
or more verbose:
const methods = _.flow([
_.add,
String.fromCharCode
]);
const forward = _.curry(methods, 2);
Note that the 2 corresponds to the amount of parameters the _.add method expects.

How do i check a count value in chai-as-promised?

I use cucumber and chai-as-promised as assertion library. What is the right way to check the count value. I use equal but it works only after converting string to integer.Is there a way to assert a integer value directly?
this.Then(/^the list should contain "([^"]*)" items$/, function (arg1, callback) {
var count=parseInt(arg1);
expect(element.all(by.repeater('item in list.items')).count()).to.eventually.equal(count).and.notify(callback);
});
If you really wanted to, I believe you could bypass parseInt() by using Chai's satisfy() method and JavaScript coercion, as shown below. However, I personally prefer the method you are currently using as it is easier to understand and coercion can be tricky.
this.Then(/^the list should contain "([^"]*)" items$/, function (arg1, callback) {
expect(element.all(by.repeater('item in list.items')).count()).to.eventually.satisfy(function(count) { return count == arg1 } ).and.notify(callback);
});

optimal way of passing multiple callback functions as arguments?

I have a function that could be used in CLI or web application, that being said, there is a little difference in the process; for example: if I'm using this function for CLI it'll use a text progress bar, but that doesn't make sense if I'm using this function for a web application.
The function is basically a loop; so what i'm looking for is a way to make this function flexible by making it possible to pass code as an argument so that it'll be executed at the end of each loop cycle. So if I'm using this function in CLI; i'll pass a progress incremental function to advance the progress bar, and so on.
My current solution is to pass a progress bar object instance, which I think isn't a proper solution; because it doesn't seem flexible for the long run.
A demonstration example of what I'm already doing:
function myFunction($progressBar = null)
{
for($i = 0; $i......)
{
//Do stuff
....
//finally...
if(!empty($progressBar))
$progressBar->advance();
}
}
So, if I want to add another function at the end of the loop, I'll have to pass it as an argument and call it manually later; but as I said, it just doesn't seem right.
I'm thinking of using a callback function(an anonymous function being passed to myFunction) But what is a proper way of doing that; should I just make each callback function as an individual argument? or, to make it even more flexible, should I be grouping all callback functions in an array(if that's possible).
Yes, you can use callbacks for this.
function myFunction($progressBar = null, callable $callback = null)
{
for($i = 0; $i......)
{
//Do stuff
....
//finally...
if(!empty($progressBar))
$progressBar->advance();
}
if ($callback){ //Execute the callback if it is passed as a parameter
$callback();
}
}
Also, you can specify parameters for an anonymous function:
Example: you want to echo something at some point.
myFunction($progressBar) ; //No need yet
myFunction($progressBar, function($result){ echo $result ; }) ; //Now you want to execute it
So, handle it in an appropriate way:
if ($callback){ //Execute the callback if it is passed as a parameter
$callback("All is fine"); //Execute the callback and pass a parameter
}
Array of callbacks also may be useful in this case like:
$callbacks = array(
"onStart" => function(){ echo "started" ; },
"onEnd" => function(){ echo "ended" ; }
) ;
function myFunc($progressBar = null, $callbacks){
if (isset($callbacks["onStart"]) && is_callable($callbacks["onStart"])){
$callbacks["onStart"]() ;//Execute on start.
}
//Execute your code
if (isset($callbacks["onEnd"]) && is_callable($callbacks["onEnd"])){
$callbacks["onEnd"]() ;//Execute on end.
}
}

Equivalent of times() in JMockIt?

I dont think minInvocation or maxInvocation is equivalent to times() in Mockito. Is there?
Please see this questions: Major difference between: Mockito and JMockIt
which has not been answered yet by anyone.
Edit
I found the answer myself: Adding it here for others who need this answered:
The solution is to use DynamicPartialMocking and pass the object to the constructor of the Expectations or NonStrictExpectations and not call any function on that object.
Then in the Verifications section, call any function on the object for which you want to measure the number of invocations and set times = the value you want
new NonStrictExpectations(Foo.class, Bar.class, zooObj)
{
{
// don't call zooObj.method1() here
// Otherwise it will get stubbed out
}
};
new Verifications()
{
{
zooObj.method1(); times = N;
}
};
I found the answer myself: Adding it here for others who need this answered:
The solution is to use DynamicPartialMocking and pass the object to the constructor of the Expectations or NonStrictExpectations and not call any function on that object.
Then in the Verifications section, call any function on the object for which you want to measure the number of invocations and set times = the value you want
new NonStrictExpectations(Foo.class, Bar.class, zooObj)
{
{
// don't call zooObj.method1() here
// Otherwise it will get stubbed out
}
};
new Verifications()
{
{
zooObj.method1(); times = N;
}
};

Chaining continuations together using .NET Reactive

Newbie Rx question. I want to write a method like the following:
public IObsevable<Unit> Save(object obj)
{
var saveFunc = Observable.FromAsyncPattern(...);
saveFunc(obj).Subscribe(result =>
{
Process(result);
return Observable.Return(new Unit());
});
}
The basic idea is: Save the given object, process the results in my "inner" continuation, then allow the caller's "outer" continuation to execute. In other words, I want to chain two continuations together so that the second one does not execute until the first one finishes.
Unfortunately, the code above does not compile because the inner continuation has to return void rather than an IObservable. Plus, of course, returning an observable Unit out of a lambda is not the same as returning it from the containing function, which is what I really need to do. How can I rewrite this code so that it returns the observable Unit correctly? Thanks.
Simplest solution is to use SelectMany
public IObsevable<Unit> Save(object obj)
{
var saveFunc = Observable.FromAsyncPattern(...);
return saveFunc(obj).SelectMany(result =>
{
Process(result);
return Observable.Return(new Unit());
});
}