Extension functions on annotated types - annotations

Is it possible to define a Kotlin extension function on a annotated type like this?
#ColorInt
fun #ColorInt Int.darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
Alternative form:
#ColorInt
fun (#ColorInt Int).darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
That would correspond to the following static funtion:
#ColorInt
fun darken(#ColorInt color: Int): Int {
return ColorUtils.blendARGB(color, Color.BLACK, 0.2f)
}
I don't think that's possible yet using Kotlin, but would it be possible to add that feature in later Kotlin versions?
On a side note:
The same question applies to #IntDef, #StringDef, #[resource type]Res as well.

Yes you can. Use the following syntax:
#ColorInt
fun #receiver:ColorInt Int.darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
More about annotation use-site targets: http://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

Related

How can I test a method and to mock another method that are in the same class in Flutter

Description:
I have already tested methodA() and methodB() so I can be sure that they are covered.
What are the ways to test methodToBeTested() by mocking methodA() and methodB() that are in the same file? The parameters are passed through the methodToBeTested() to the methodA() and methodB() to properly test these methods using injection.
Note: They are cannot be extracted to a different class since it is a related logic of the calculation service and these methods are already atomically is separated.
Code:
class ClassForTesting {
int methodToBeTested(String a, String b) {
// Calculation in this method also is a bit more difficult
return methodA() + methodB();
}
int methodA(String a) {
int value = 1;
// Here is calculation logic that has been tested
return value;
}
int methodB(String b) {
int value = 2;
// Here is calculation logic that has been tested
return value;
}
}
What has been done:
I have tried several approaches from Mockito, but it doesn't allow to do such a trick:
#GenerateMocks - is creating a mock and requires me to stub each method using when(), even methodToBeTested().
By extending Fake using the next construction:
class Mock extends Fake implements PasswordValidatorService {}
But in this way, I'm only inheriting the PasswordValidatorService's behavior instead of instead implementation and each non-overridden method throws UnimplementedError. Thus, I'm not able to override methodToBeTested() and call its super implementation.
I found that Mockito for Java has #Spy construction that would be perfect in this case but unfortunately it is not available for Dart and Flutter.
The only way I currently came is to create my own Mock:
class MockClassForTesting extends ClassForTesting {
#override
int methodA() {
return 2;
}
#override
int methodB() {
return 5;
}
}
But this implementation doesn't allow me to use Mockito's flexibility of when() construction since I must have different methodA() and methodB() returns.
This fact forces me to have additional variables in my MockClassForTesting to achieve when() construction functionality.
The questions:
What would be the best way to achieve my purposes?
Can be the same mocking approach to be used during the Widget testing?
One approach would be to use a hybrid approach where you create your own derived class but where some of its overrides delegate to a Mock implementation. For example:
class ClassForTesting {
int methodToBeTested(String a, String b) {
// Calculation in this method also is a bit more difficult
return methodA(a) + methodB(b);
}
int methodA(String a) {
int value = 1;
// Here is calculation logic that has been tested
return value;
}
int methodB(String b) {
int value = 2;
// Here is calculation logic that has been tested
return value;
}
}
class PartialMockClassForTesting extends ClassForTesting {
final mock = MockClassForTesting();
#override
int methodA(String a) => mock.methodA(a);
#override
int methodB(String b) => mock.methodB(b);
}
#GenerateMocks([ClassForTesting])
void main() {
test('Test partial mock', () {
var partialMock = PartialMockClassForTesting();
when(partialMock.methodA('hello')).thenReturn(42);
when(partialMock.methodA('goodbye')).thenReturn(-42);
when(partialMock.methodB('world')).thenReturn(10);
expect(partialMock.methodToBeTested('hello', 'world'), 52);
expect(partialMock.methodToBeTested('goodbye', 'world'), -32);
});
}
If you want to conditionally mock certain methods, you could have your overrides check boolean flags to conditionally call either the mock or the real implementation. For example:
class PartialMockClassForTesting extends ClassForTesting {
final mock = MockClassForTesting();
final shouldMock = <Function, bool>{};
#override
int methodA(String a) =>
shouldMock[methodA] ?? false ? mock.methodA(a) : super.methodA(a);
#override
int methodB(String b) =>
shouldMock[methodB] ?? false ? mock.methodB(b) : super.methodB(b);
}
#GenerateMocks([ClassForTesting])
void main() {
test('Test partial mock', () {
var partialMock = PartialMockClassForTesting();
partialMock.shouldMock[partialMock.methodA] = true;
partialMock.shouldMock[partialMock.methodB] = true;
...

How to port a complicated abstract class to swift?

I have an abstract class in my mind and I can't implement its several features in swift, so I use C++ to deliver my thoughts:
template <class T>
class Swapping {
public:
void swap() { _foregroundIndex = backgroundIndex() }
virtual void cleanup() = 0;
T* foreground() { return _buffer[foregroundIndex()]; }
T* background() { return _buffer[backgroundIndex()]; }
void setForeground(T* foreground) { _buffer[foregroundIndex()] = foreground; }
void setBackground(T* background) { _buffer[backgroundIndex()] = background; }
private:
short foregroundIndex() { return _foregroundIndex; }
short backgroundIndex() { return _foregroundIndex ^ 1; }
short _foregroundIndex = 0;
T* _buffer[2] = {NULL, NULL};
}
The main contradiction is that
The pure virtual method cleanup() requires all subclasses to implement it explicitly (can achieve in swift with protocol)
The instance variable _foregroundIndex has an initial value (cannot achieve using protocol)
The instance variable _foregroundIndex is restricted to be private ( cannot achieve using protocol)
On the other hand, if I use a class instead of protocol, then I can't guarantee cleanup() method is overriden.
One may suggest that put the virtual method in a protocol and the instance variable in a class. That may work but is not a obsession-satisfying one.
P.S. Objective-C is not Swift. Any objc_runtime related workaround is not preferred.
There’s an obvious solution, which I have seen often but will certainly not satisfy you is:
func cleanup() {
fatalError("You must override cleanup()")
}
Then you could try using extensions to extend the protocol with default implementations, but extensions don’t allow stored properties and so you would most likely need some external objects or other magic you certainly also dislike.
As I noted above in the comments, you might need to rethink your design. I don’t know what you really intend to do, but maybe something like this would work out for you:
class Swapper<T> {
private var foregroundIndex = 0
private var backgroundIndex: Int {
return foregroundIndex ^ 1
}
private var buffer: [T?] = [nil, nil]
private let cleanupHandler: () -> ()
init(cleanupHandler: #escaping () -> ()) {
self.cleanupHandler = cleanupHandler
}
func cleanup() {
cleanupHandler()
}
var foreground: T? {
get {
return buffer[foregroundIndex]
}
set {
buffer[foregroundIndex] = newValue
}
}
var background: T? {
get {
return buffer[backgroundIndex]
}
set {
buffer[backgroundIndex] = newValue
}
}
func swap() {
foregroundIndex = backgroundIndex
}
}
This makes more sense to me as this allows any types to be swapped with any clean up handler, without having to subclass the class every time.

How to instantiate an anonymous class that implements an interface in Kotlin

In Java, instantiate an interface object is as easy as new Interface()... and override all the required functions as below, on AnimationListener
private void doingSomething(Context context) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
animation.setAnimationListener(new Animation.AnimationListener() {
// All the other override functions
});
}
However, in Kotlin when we type
private fun doingSomething(context: Context) {
val animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
animation.setAnimationListener(Animation.AnimationListener(){
// All the other override functions
})
}
It error complaints unresolved References AnimationListener.
As explained in the documentation:
animation.setAnimationListener(object : Animation.AnimationListener {
// All the other override functions
})
Apparently the latest way (using Kotlin 1.0.5) of doing it is now without the parenthesis, given there's no empty constructor for the interface.
animation.setAnimationListener(object : Animation.AnimationListener {
// All the other override functions
})

Where did Option[T] come from in Scala?

I'm still a noob in Scala development but I have found the Option[T] concept really awesome, specially the pattern matching when used with Some and None. I am even implementing it so some extent in a C# project I'm working on at the moment, but as there is no pattern matching in there is isn't really that awesome.
The real question is, where is the theory behind this object? is it something specific from Scala? Funcional languages? Where can I find more about it?
Most of the time I was thinking that it comes from the Haskell, and has a name of Maybe monad
But after a little research, I've found that there was some references on option types in SML papers, as #ShiDoiSi said. Moreover, it has the same semantics (Some/None) that Scala has.
The elderest paper I was able to find is that (circa '89) (see footnote on the 6th page)
You don't need pattern-matching to use Option. I have written it in C# for you below. Note that the Fold function takes care of anything that would otherwise be pattern-matched.
Pattern-matching is generally discouraged in favour of higher-level combinators. For example, if your particular function can be written using Select you would use it rather than Fold (which is equivalent to pattern-matching). Otherwise, assuming side-effect free code (and therefore, equational reasoning), you would essentially be re-implementing existing code. This holds for all languages, not just Scala or C#.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Example {
/// <summary>
/// An immutable list with a maximum length of 1.
/// </summary>
/// <typeparam name="A">The element type held by this homogenous structure.</typeparam>
/// <remarks>This data type is also used in place of a nullable type.</remarks>
public struct Option<A> : IEnumerable<A> {
private readonly bool e;
private readonly A a;
private Option(bool e, A a) {
this.e = e;
this.a = a;
}
public bool IsEmpty {
get {
return e;
}
}
public bool IsNotEmpty{
get {
return !e;
}
}
public X Fold<X>(Func<A, X> some, Func<X> empty) {
return IsEmpty ? empty() : some(a);
}
public void ForEach(Action<A> a) {
foreach(A x in this) {
a(x);
}
}
public Option<A> Where(Func<A, bool> p) {
var t = this;
return Fold(a => p(a) ? t : Empty, () => Empty);
}
public A ValueOr(Func<A> or) {
return IsEmpty ? or() : a;
}
public Option<A> OrElse(Func<Option<A>> o) {
return IsEmpty ? o() : this;
}
public bool All(Func<A, bool> f) {
return IsEmpty || f(a);
}
public bool Any(Func<A, bool> f) {
return !IsEmpty && f(a);
}
private A Value {
get {
if(e)
throw new Exception("Value on empty Option");
else
return a;
}
}
private class OptionEnumerator : IEnumerator<A> {
private bool z = true;
private readonly Option<A> o;
private Option<A> a;
internal OptionEnumerator(Option<A> o) {
this.o = o;
}
public void Dispose() {}
public void Reset() {
z = true;
}
public bool MoveNext() {
if(z) {
a = o;
z = false;
} else
a = Option<A>.Empty;
return !a.IsEmpty;
}
A IEnumerator<A>.Current {
get {
return o.Value;
}
}
public object Current {
get {
return o.Value;
}
}
}
private OptionEnumerator Enumerate() {
return new OptionEnumerator(this);
}
IEnumerator<A> IEnumerable<A>.GetEnumerator() {
return Enumerate();
}
IEnumerator IEnumerable.GetEnumerator() {
return Enumerate();
}
public static Option<A> Empty {
get {
return new Option<A>(true, default(A));
}
}
public static Option<A> Some(A t) {
return new Option<A>(false, t);
}
}
}
Wikipedia is your friend: http://en.wikipedia.org/wiki/Option_type
Unfortunately it doesn't give any dates, but I'd bet that it's ML-origin predates Haskell's Maybe.

Question about var type

I am new to C# 3.0 var type. Here I have a question about this type. Take the following simple codes in a library as example:
public class MyClass {
public var Fn(var inValue)
{
if ( inValue < 0 )
{
return 1.0;
}
else
{
return inValue;
}
}
}
I think the parameter is an anonymous type. If I pass in a float value, then the Fn should return a float type. If a double value type is passed in, will the Fn return a double type? How about an integer value type as input value?
Actually, I would like to use var type with this function/method to get different return types with various input types dynamically. I am not sure if this usage is correct or not?
You can't use var for return values or parameter types (or fields). You can only use it for local variables.
Eric Lippert has a blog post about why you can't use it for fields. I'm not sure if there's a similar one for return values and parameter types. Parameter types certainly doesn't make much sense - where could the compiler infer the type from? Just what methods you try to call on the parameters? (Actually that's pretty much what F# does, but C# is more conservative.)
Don't forget that var is strictly static typing - it's just a way of getting the compiler to infer the static type for you. It's still just a single type, exactly as if you'd typed the name into the code. (Except of course with anonymous types you can't do that, which is one motivation for the feature.)
EDIT: For more details on var, you can download chapter 8 of C# in Depth for free at Manning's site - this includes the section on var. Obviously I hope you'll then want to buy the book, but there's no pressure :)
EDIT: To address your actual aim, you can very nearly implement all of this with a generic method:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
As shown in the listing, the tricky bit is working out what "1" means for an arbitrary type. You could hard code a set of values, but it's a bit ugly:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
Icky - but it'll work. Then you can write:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
etc
You cannot use var as a return type for a method.