unit-testing,delphi,generics,dunitx
Try to make your test class generic and register your test class with every single concrete type you want to test. [TestFixture] TMyTestObject<T> = class(TObject) public // Sample Methods // Simple single Test [Test] procedure Test1; // Test with TestCase Atribute to supply parameters. [Test] [TestCase('TestA','1,2')] [TestCase('TestB','3,4')] procedure Test2(const AValue1...
c#,generics,unity,dependency-resolver
ResolveAll only resolves named registrations, try registering your handler with a name, like so: container.RegisterType<IDomainEventHandler<ProductCreated>, ProductCreatedHandler>("ProductCreatedHandler", new PerRequestLifetimeManager()); This can be seen under Remarks in the documentation for ResolveAll<T>(): Be aware that this method does NOT return an instance for the default (unnamed) registration. ...
You've got two options: Introduce V as a type parameter to the class. public class Test<V> Introduce V as a type parameter to that function. public <V> void genericTest(Map<String, V> params) ...
You can use generics to say that you expect an object that has both characteristics private <T extends Shape & Fillable> void setFilledAndAdd(T obj, Color color, int x, int y){ obj.setFilled(true); // needs interface Fillable obj.setFillColor(color); add(obj, x, y); } private void add(Shape s, int x, int y){ // whatever...
That is not possible and it wouldn't really make sense. You could never rely on T having certain members available because it could be A or B. All members are optional then. It certainly is conceivable to have this feature but it goes against the spirit of generics. This would...
As matt already explained, you cannot define an initializer which is restricted to types implementing a protocol. Alternatively, you could define a global function instead: public protocol Nameable { static func entityName() -> String } func createInstance<T : NSManagedObject where T: Nameable>(type : T.Type, context : NSManagedObjectContext) -> T {...
We can use enable_if here if you have C++11 or higher available to you template<typename T, typename std::enable_if<std::is_base_of<MyClass, T>::value>::type* = nullptr> T Foo(T bar) { return T(); } For example: class MyClass { public: int a = 1; }; class Derived : public MyClass { public: int b = 2;...
You can abuse interfaces and variance to achieve that: public interface IState<out TObject, in TState> where TObject : IStatefulObject<TObject, TState> where TState : IState<TObject, TState> { } public interface IStatefulObject<in TObject, out TState> where TObject : IStatefulObject<TObject, TState> where TState : IState<TObject, TState> { } public abstract class AbstractState<TObject> :...
java,generics,compare,comparable
I know the data value will be a object-wrapped primitive or a String, so they are comparable. Then you can tell the compiler about it: public class TreeNode<T extends Comparable<T>> If you do that, you will get access to the compareTo method defined in Comparable....
I don't think there is a way to write the function as such with Manifest, ClassTag or a TypeTag as they can only tell you the type at runtime. For something like the pseudocode function to work, the return type must be known at compile time. However, could implement the...
Your method signature needs a type parameter: public static Stack<T> ToStack<T>(this IEnumerable<T> source) As a sidenote, this won't compile once you fix that. You need to call the Count() method on IEnumerable: var returnStack = new Stack<T>(reversed.Count()); Also as @Servy points out in the comments, the check for whether this...
The problem you're having is that public class Entity<TEntitySchema> is generically invariant. That means that even though you know that ContactEntitySchema : EntitySchema that doesn't mean the compiler can substitute ContactEntitySchema for EntitySchema in the generic type definition for ViewBase. (To understand why that's the case, consider what happens if...
c#,database,generics,inheritance,abstract-class
The key here is to step back and think about the problem from another angle. You are duplicating lots of code because you are creating instances of the database and command classes within the method. So inject them instead: public class SomeDBClass { static DataTable exec_DT(DBConnection conn, DBCommand cmd) {...
You can make your code generic with something like this: var size = Marshal.SizeOf(typeof(T)); var subBuffer = new byte[size]; Array.Copy(Buff, Peek, subBuffer, 0, size); var handle = GCHandle.Alloc(subBuffer, GCHandleType.Pinned); var ptr = handle.ToIntPtr(); var val = (T)Marshal.PtrToStructure(ptr, typeof(T)); ptr.Free(); Peek += size; Peek = ( Peek + ( Align -...
java,generics,equality,string-comparison,method-signature
Because equals() is declared in Object and compareTo(T foo) is defined in Comparable<T>. Before generics the issue was the same with Comparable, compareTo taking an Object argument, but since there's no "Equalable" interface there was no place to stick the generic parameter....
Let me detalize Alexey's answer. Here is full implementation with some code style improvements: First define your trait with aknowledgment of it's covariance: trait Tree[+T] { def contains[U >: T : Ordering](num: U): Boolean def inc[U >: T : Ordering](num: U): Tree[U] } Next define your subtype-of-all-trees object case object...
I think that best solution for your case would be changing class declaration to: class EventDispatcher<U: EventDispatcherProtocol> { typealias KeyType = U.T And it will also simplify creation of the EventDispatcher with skipping the redundant type declarations: var dispatcher = EventDispatcher<CustomListener<CustomEvent>>() EDIT: Since the code was altered multiple times while...
Treat it like any other generic code you've read. Here's the formal signature from what I see in Java 8's source code: public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X X has an upper bound of Throwable. This will be important later on. We return a type...
scala,generics,types,implicit-conversion
You've just told the compiler that types passed to your class as T and S should be equal - you just require an evidence of their equality, which can be used to infer actual T and S correctly when you pass actual types (but not inside generic class itself). It...
The problem is that when you call addShape(someColl, new Circle()); there are two different definitions of T ? extends Shape from Collection<? extends Shape> someColl Circle from the second parameter The other problem with that call is that T needs to be a concrete type for the second parameter, i.e....
java,generics,compiler-warnings,unchecked
Your types are raw - that is, your generic types are bonded to a type that itself has a type, but you haven't provided one, so it's raw. Change your type bounds to be typed. Try this: public abstract class AbstractPresenter<V extends AbstractView<V>, M> implements Presenter<V, M> and public abstract...
You'll need a type parameter for the Collection element type, potentially a type parameter for the actual Collection type if you need it, and a type parameter for the values. class SubClass<E, K extends Collection<E>, V> implements Map<K, V> { ... } If you don't need the specific Collection type,...
generics,sharepoint-2010,.net-3.5
C# is a case-sensitive language. You defined a class ListColumns, but you're referring to it as listcolumns. That won't work....
Seems like this is what you're trying to achieve: case class SomeClass(name: String) abstract class Factory[U]() { protected def create(name: String) : U } class SomeFactory extends Factory[SomeClass] { def create(name: String) = SomeClass(name) } (I'm assuming you meant for SomeFactory to extend Factory)...
This may not be the answer you are looking for, as I haven't done much Haskell, but it's a possibility: You can define a trait that can only be mixed into specific instances of a tree: trait StringFooFunctionality { this: Tree[String] => // Selftype, can only be mixed in to...
1. Generics is all about code safety without knowing the type on compile time. That means it would make no sense to initialise a generic type to something. However by declaring a protocol like protocol Initializable { init() } , extending the types you want to use by doing extension...
If you know the type at startup, you could just derive the class: public class UserLogin : GenericLogin<ABC01_REGISTERED_USER> { } Then use that class all along. Else, you have to supply the type name every time, since else it can't know that you want to use that type every time....
c#,linq,generics,azure,reflection
Answering on original question how to rewrite this in generic way with reflection, so that method should not require changes for every new social network. If MySpace gonna be handled, you need just to add it to handlerMapping, HandleAnySocialNetworkByMapping() not changing (see code below). class Program { private readonly static...
java,json,generics,reflection,gson
see here a default implementation of ParametrizedType: http://www.java2s.com/Code/Java/Generics/DefaultimplementationoflinkjavalangreflectParameterizedType.htm properly prepared, such a type could be used to represent a generic type, which may work with GSON. Without having tested it, your code might then look like this: File root = new File("./build/classes"); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });...
You can use map to cast each element to the desired type: protocol MyProtocol { var x: Int { get } } class MyClass : MyProtocol { var x: Int = 5 } var classArr: [MyClass] = [MyClass(), MyClass()] var protocolArrA:[MyProtocol] = classArr.map{$0 as MyProtocol} var andBack:[MyClass] = protocolArrA.map{$0 as!...
c#,.net,generics,type-constraints
Sounds like you're just missing the ability to specify both a class and interfaces as a comma-separated list in the constraints: static void INeedToDoBoth<T>(T dependency) where T : Dependency, IOptionalDependency Note that the class constraint must come first here. See the MSDN page for type parameter constraints or the C#...
Swift's static typing means the type of a variable must be known at compile time. In the context of a generic function func foo<T>() { ... }, T looks like a variable, but its type is actually known at compile time based on where the function is called from. The...
The definition of your BinarySearchTree is: public class BinarySearchTree<Element> extends Tree<Element, Node<Element>> Here, Element is a type-parameter, but not the actual type Element. It's pretty much the same, as you did: public class BinarySearchTree<T> extends Tree<T, Node<T>> Now the error you're getting makes more sense: The type T is not...
To quote the C# 5.0 specification §18.2 Pointer Types Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data to which they point. For this reason a pointer is not permitted to point to a reference...
Here, you're defining two type-parameters: T extends Renderable Box Box is the alias of the second method-scoped type-parameter and if you have another one with the same name (class-scoped), the method-scoped one will hide it. That's why Eclipse throws a warning. If you want T to extend both Renderable and...
c#,generics,compiler-errors,ado.net
You need to tell what is "T" to the method, right now your method does not know what T is. T is known at compile time, the language does not figure out the type on the spot. Here's an example: static List<T> GetInitializedList<T>(T value, int count) Reference here: http://www.dotnetperls.com/generic-method...
r,generics,s4,equality-operator
Thanks to MrFlick's response: It turns out that == is already generic (implement in C). So you don't need to call setGeneric. Rather, you can just use setMethod. setMethod("==", c(e1="Class1",e2="Class2"), funciton(e1,e2) { .... }) ...
java,arrays,algorithm,generics,reverse
If you mean that you want to do it manually without using Collections.reverse (that code shouldn't even compile btw, reverse needs a List as parameter), just traverse the array from the beginning to the middle swapping elements at the opposite sides of the range: public E[] reverse() { for (int...
Why don´t you leave out the C-param at all? public static IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int count) { return list.Skip (count).Concat(list.Take(count)); } EDIT: As Suresh Kumar Veluswamy already mentioned you may also simply cast your result to an instance of C: public static C RotateLeft<C, T>(C list, int count) where C...
If you have an option of passing additional param to your function, you can do following: def minCasted[A](caster: String => A)(rdd: RDD[Map[String, String]], field: String): A = { caster(rdd.map(_(field)).min()) } def minDouble = minCasted(_.toDouble) _ def minString = minCasted(identity[String]) _ ...
You can't restrict generics in that way, you can only choose a single class as a constraint. You must either make 5 overloads or find a interface all 5 of those things share and use that. Which option you choose will depend on what Validate doe. Here is how you...
I quickly fixed it by putting explicit generic parameters on SelfLink public class SelfLink<MODEL,MESSAGE extends LinkedMessage> implements ToMessageOperation<MODEL, MESSAGE> { @Override public void run(MODEL object, MESSAGE linkedMessage) throws Exception { linkedMessage.linkme(); } } public <MODEL,MESSAGE extends LinkedMessage> SelfLink<MODEL, MESSAGE> selfLink() { return null; } Using the factory class for selflink,...
c#,entity-framework,generics,constructor
All Entities linked to EntityFramework must have a Default Constructor. When Entity Framework maps from a database query to your Entities use the default constructor to instantiate a new instance of your Entity to fill it with the data retrieved from your database. If you don't have a default constructor...
I solved like this; IList targetList = (IList)listPropertyInfo.GetValue(item); Type foo = targetList.GetType().GenericTypeArguments.Single(); Type unboundGenericType = typeof(READ<>); Type boundGenericType = unboundGenericType.MakeGenericType(foo); MethodInfo doSomethingMethod = boundGenericType.GetMethod("trigger"); object instance = Activator.CreateInstance(boundGenericType); doSomethingMethod.Invoke(instance, new object[] { targetList, f, properties }); ...
In this method private <T> int comp(Comparable<T> upper, Comparable<T> lower){ return upper.compareTo((T) lower); } both of the parameters share the same type-parameter. Meanwhile, this is not true for the other method: private int compare (Comparable<?> upper, Comparable<?> lower){ return comp(upper, lower); } Here, the compiler has no evidence that the...
From other research (Equals(item, null) or item == null and Unity Forums) and to elaborate on usr's answer: I needed to guarantee that a Component was being passed through in my CheckIfNull header. The updated code looks like this: using UnityEngine; using System.Collections; public class NullChecker : MonoBehaviour { void...
In EdgeWeightedGraph, this line does not create a generic array. adj = new Bag[V]; It is creating an array of a raw type, which is allowed. Bag is a class, not a type parameter. However, in MinPQ, Key is a type parameter, not a class, so this line attempts to...
I think you have to parametrise MyClass: type MyClass<'T> = interface IMyInterface with member this.Method s = let i = s.IndexOf "a" if i = -1 then raise (new MyException<'T> ()) i or repeat constraints on your method: type MyClass = interface IMyInterface with member this.Method<'T when 'T : (new:...
I ended up with the following code ParameterizedType targetMapParameterizedType = (ParameterizedType) targetMethodMap.get(targetMethodName).getGenericParameterTypes()[0]; Class<?> mapType = targetMethodMap.get(targetMethodName).getParameterTypes()[0]; if(mapType.isInterface()) { newMap = new HashMap<Object, Object>(); } else { try { newMap = (Map<Object, Object>) mapType.newInstance(); } catch(Exception e) { newMap = new HashMap<Object, Object>(); } } Class<?> targetKeyType = null; Class<?> targetValueType...
In C++11, you can do something like this template<typename T> using fun_ptr = void (*)(T); And for the second case, template<typename... T> using fun_ptr = void (*)(T ...); ...
I don't think so these warnings would hang your IDE, these are harmless. And also it is always a best practice to specify the type for generics like Vectar<Object> or Vectar<String> or List<String> or ArrayList<String> etc and not use raw types. Please read from updated sources and books. It is...
c#,generics,icollection,keyvaluepair
Note beforehand : As a personal preference I tend to use dictionary for key/value pairs with unique keys or multimap/ilookup when i need duplicate key inputs. If you use C# 3.5 or older you can use var dic = new Dictionary<string, object>(); Assuming you're on C# 4 you can use...
You have a wildcard in the type parameter of your handler variable. The compiler doesn't know what the exact type of this type parameter is, only that it's either Monitor or a subclass. The call method takes a T, which is matched on the wildcard. But there is no guarantee...
c#,entity-framework,generics,reflection
Try var obj = methodinfo.Invoke(null, new[] { employees }); The OfType is static, so null obj (the first parameter of Invoke, that is the instance of the object to use for the method)!...
java,generics,collections,super,contravariance
This is a faulty assumption: because the operation is bound to fail because of its types, which are known at compile-time It's the same reasoning that .equals accepts an object: objects don't necessarily need to have the same class in order to be equal. Consider this example with different subtypes...
You got it the wrong way around. Each T is a Bar, but not each Baris a T. T is more specialized than Bar (each dachshound is a dog, but not each dog is a dachshound). This means, that return Optional.ofNullable(array[index]); tries to match a Bar on a T, which...
c++,templates,c++11,generics,sfinae
In essence, the equivalent of if ... else if with SFINAE. You can manually control overload resolution with an extra parameter: template<int I> struct rank : rank<I-1> { static_assert(I > 0, ""); }; template<> struct rank<0> {}; template <class A, class B> auto foo(A& a, B& b, rank<10>) ->...
In Castle Windsor you can use such code : public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>)) } ); public class Repository<T> : IRepository<T> where T : class, IEntity { ... } Therefore I find registering and resolving generics pretty simple for registering and resolving generics with interfaces. There...
ios,objective-c,xcode,generics
The lightweight generics introduced in Xcode 7 are just compile time hints to help the compiler raise warnings, but at run time you get the same old behavior with your variable being just NSArrays of ids. Source: WWDC '15 "Swift and Objective-C Interoperability" session See the transcript of the talk:...
C# Generics simply does not allow you to specify a subset of the type parameters. It's all or nothing. The way to work around this is to write a fluent interface. You break this operation up into a chain of methods. public class FirstPropertyWithTypeSelector<T> { private readonly IQueryable<T> _source; public...
c++,templates,generics,constraints
you usually make constraints on C++ template with std::enable_if here is the trick - if your template looks like this: template <class T> <return type> <function name> (args...) you take the return type and corporate it with enable_if like this : template <class T> typename std::enable_if<XXX,<return type>>::type <function name> (args...)...
This looks like a known compatibility issue reported here and here. From the second link: The following code which compiled, with warnings, in JDK 7 will not compile in JDK 8: import java.util.List; class SampleClass { static class Baz<T> { public static List<Baz<Object>> sampleMethod(Baz<Object> param) { return null; } }...
You can define two type parameters: public interface GenCarry<K extends GenCarry<K, T>, T extends Gen<T, K>> { GenCarry<K, T> setGen(T gen); } public interface Gen<K extends Gen<K, T>, T extends GenCarry<T, K>> { void applyOn(T carry); } class StringGenCarry implements GenCarry<StringGenCarry, StringGen> { @Override public StringGenCarry setGen(StringGen client) { ......
It can't be done, but…let's suppose for a moment that we could figure out a way for the following statement to compile in the way that you want: var myObject = MyMethod(); Then what is the code using myObject going to look like? In this hypothetical scenario, the variable myObject...
You have several possibilites: change return type of getPath to IEnumerable... Use only first element of the query result: Add .FirstOrDefault() var res = pathsQuery.Results.FirstOrDefault(); Generally it is a good idea to set a breakpoint and put the mouse over var to inspect what type it is. Even better to...
Introducing an interface will allow you to take advantage of Covariance in the generic declaration. This will allow Building to be treated as Building which is ultimately what you are wanting to achieve. Note that only interfaces support this via the 'out' modifier: public class Person { public Person() {...
This is technically doable with the unsafe raw cast Set<Map.Entry<K, V>> unionSet = ImmutableSet.of(); for(Map<? extends K, ? extends V> map : chain) { unionSet = Sets.union((Set) map.entrySet(), unionSet); } ...and that is almost certainly the best way to provide a live view of the union of the entry sets....
c#,generics,extension-methods,ienumerable
Here is another attempt, inspired from Eric Lippert's excellent post at: http://stackoverflow.com/a/1451184/4955425. You can control the overloading resolution by placing your 2 extension methods at different levels in the namespace hierarchy. namespace MyExtensions { public static class HighPrecendenceExtensions { public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this IEnumerable<TSource> source) { return source; } }...
c#,entity-framework,generics,mapping,nullable
Entity Framework generally maps classes to database tables and properties of your entity classes to database column types depending on your provider. (For example, you can see a mapping of CLR types to SQL Server here though I'm not sure if that's what the EF SQL Server provider uses.) Your...
You need to use a type parameter to say that two 'unknown' types are the same. I thought that maybe you should change your method signature from: static <T> void sort(List<T> data, final Key<T, ?> key[], final int dir[]) to static <T,U> void sort(List<T> data, final Key<T,U> key[], final int...
You could pass the multiply and decrement functions to a generic method: private static Map<Number, Number> factorials = new HashMap<> (); private static <T extends Number> T factorial(T n, BinaryOperator<T> multiply, UnaryOperator<T> decrement) { if (n.doubleValue() == 1) return n; T result = (T) factorials.get(n); if (result == null ){...
java,spring,spring-mvc,generics,casting
You should probably use a common interface shared by both classes. Declaring an interface like, for instance: public interface INotes{ } public class GroupNotes implements INotes{...} public class Notes implements INotes{...} Your code would become: @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/findnotebydays/{days}/{canvasid}/{mode}") public @ResponseBody List<INotes> findNotesByDays(@PathVariable("days")int days, @PathVariable("canvasid")int canvasid, @PathVariable("mode")boolean mode ){ if(!mode){...
You have to use the generator type as the type placeholder G, and refer to its element type as G.Element: class MyGenericClass<G : GeneratorType> { var source : G var itemsProcessed : [ G.Element ] = [] init(source: G) { self.source = source } func getValue() -> G.Element? { let...
The capture of a wildcard type is a type that is used by the compiler represent the type of a specific instance of the wildcard type, in one specific place. Example: Take for example a method with two wildcard parameters, void m(Ex<?> e1, Ex<?> e2). The declared types of e1...
In this particular case it's because the List.set(int, E) method requires the type to be the same as the type in the list. If you don't have the helper method, the compiler doesn't know if ? is the same for List<?> and the return from get(int) so you get a...
java,generics,iterator,override,abstract
Don't have the Collection implement Iterator. That's for the Iterator instance. Your concrete collection needs to extend AbstractCollection, and your NameIterator implements Iterator. class Name<E extends Comparable<E>> extends AbstractCollection { @Override public NameIterator<E> iterator() { return new NameIterator<>(); } @Override public int size() { return 0; } } class NameIterator<E...
It seems that Actor and Role are the same field internally. Setting it to actor then setting it to null means that it's null. The recipient of that data, known as the SOAP Role in version 1.2 of the SOAP specification and the SOAP Actor in version 1.1 ...
scala,generics,types,typeclass,type-parameter
You can provide an implicit function with the required type: implicit def SeqMonoid[T]: Monoid[Seq[T]] = new Monoid[Seq[T]] { override def op(a: Seq[T], b: Seq[T]): Seq[T] = a ++ b override def id: Seq[T] = Nil } ...
An rlib is a regular static library (built in the ar format) that contains additional metadata. That metadata contains, among other things, the complete, serialised abstract syntax tree (AST) for all generics and functions marked with #[inline]. It's a bit like if there was a C++ compiler that shoved a...
The error message comes from the fact that R is not within its bounds. Your ViewModelHelper class extends AbstractViewModel<IRefreshPostViewCallback>, no matter what R1 really is. In the class ViewModelHelper, change the type argument in the extends clause of AbstractViewModel to R1, instead of IRefreshPostViewCallback. public abstract class RefreshPostViewModel<R1 extends IRefreshPostViewCallback>...
c#,generics,inversion-of-control,simple-injector
The solution you need is a bit dependent on how the consumer of the Dispatcher to call events. If the consumer always knows the exact type of the event at compile time, you can use the generic Dispatch<TEvent>(TEvent) method as you show above. In that case the Dispatcher's implementation will...
Does this what you want?: Func<int, int> a = p0 => p0 << 1; Func<int, int, int> b = (p0, p1) => p0 + p1; Delegate da = a; Delegate db = b; var inner = da.Method.GetParameters().Length < db.Method.GetParameters().Length ? da : db; var outer = inner == da ?...
You want to bind open generic types, so this type definition should do the trick: <bind service="Base.IJsonProvider`1, Base" to="Base.JsonProvider`1, Base" name ="Config"/> ...
java,generics,iterable,raw-types
When you made your OC_GuillotinePacker class generic, with type parameter T, your declaration became raw. packer = new OC_GuillotinePacker(0, 0, width, height); When you use a raw type, type erasure occurs, such that the iterator() method now returns a raw Iterator, which returns Objects. An Object can't be assigned to...
Okay, I should have come to realise that the typecasting that automatically occurs at compile time to prevent incompatible types is actually implicit and internal. And so it is different to the typecasting which I was referring to in the latter part my question, which is a runtime check feature....
generics,inheritance,anonymous-function,nim
The problem is that type class constraints for type parameters currently do not match subtypes; I do not know if that is a bug or intentional. For now, simply remove the : Base constraint from the type parameter T.
Make the method generic. void TransformBiscuit<T>(List<T> biscuitBarrelBiscuits) This is assuming that a single instance of BiscuitTransformer will be able to transform any top of biscuits that you would pass in, of course....
This is one of the tricky areas of Generics. The only way to get this to work would be to take a Class argument, so the method knows what type of object to create. It can't know at the moment, because of Type Erasure. Alternatively (much simpler) is to always...
<T> is not a return type. It's a declaration of the generic type parameter used by the method. Once it's declared, it can be used in the method signature without the <>;
java,generics,reference,generic-collections,raw-types
Map<Object,Object> map2 = new HashMap<String,String>(); As per my understanding Map map1 is same as Map<Object,Object> map1 No. A Map is not the same as a Map<Object,Object>. A reference of type HashMap<T,T> is a subtype of a reference of type Map. In other words, a reference of type Map can...
swift,generics,protocols,type-inference
@Roman Sausarnes' answer is correct, but instead of having the method instance, you could instead use an initialiser: protocol Prot { func doSomething() init() } class Classy: Prot { func doSomething() { println("Did something") } // The required keyword ensures every subclass also implements init() required init() {} } func...
This one: Box<Integer> integerBox = new Box(); assigns a raw Box to integerBox, bypassing generic type checks. While that might look fine in this case, it isn't so great when you have something like List<String> strings = Arrays.asList("a", "b", "c"); ... List<Integer> integers = new ArrayList(strings); If you do List<Integer>...
java,function,generics,java-8,overloading
The example you present in your question has got nothing to do with Java 8 and everything to do with how generics work in Java. Function<T, Integer> function and Function<T, Double> function will go through type-erasure when compiled and will be transformed to Function. The rule of thumb for method...
This isn't something you're going to want to do often (since generics and arrays don't mix well), but there are some important things to make note of: T holds the type information for the method. You may not be passing in a City at all times, and in the off...
java,generics,interface,architecture
It looks like what you want is : public class B<S,T extends A<S>> { private T t; public S getTsSomething(){ return t.f1(); } } ...
You were so close! Use your second (nongeneric) implementation, and: if entity.dynamicType === type { ...