FAQ Database Discussion Community


Register return Type

c#,generics,return-type
We have a C# class that holds session values for user in an MVC web application. Now I want to make the class more generic. Until now we have getters and setters for the session like public class WebAppLogin { public static WebAppLogin Current { get; //Gets the current Login...

Generic constraint of X AND Y

c#,.net,generics,type-constraints
Can generic constraints be used to enforce a constraint on type derivatives of an abstract class, but only those that implement an interface? Example: abstract class Dependency { public abstract void IMustDoThis(); } interface IOptionalDependency { void IMightDoThis(); } sealed class AlmightyDependency : Dependency, IOptionalDependency { // I have sealed...

Implementing Iterator for abstractCollection

java,generics,iterator,override,abstract
Hi I want to implement the iterator for a class that extends abstract Collection. class Name<E extends Comparable<E>> extends AbstractCollection<CompRational> implements Iterable<E>{ ... public Iterator<E> iterator(){ return new NameIterator<E>(this); } ... } and the Iterator should look like this class NameIterator<E extends Comparable<E>> implements Iterator<E>{ private Name<E> tree; private int...

throws x extends Exception method signature

java,exception,generics
Reading the JavaDoc of Optional, I bumped in a weird method signature; I never saw in my life: public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable At first glance, I wondered how the generic exception <X extends Throwable> is even possible, since you can't do...

How to refactor repeated code using reflection

c#,linq,generics,azure,reflection
So I have this large switch statement which is essentially the same code repeated multiple times where the only thing changing is the cast to a specific class. I've been trying to figure out a way to refactor it using reflection so I only have to write it once. switch(provider)...

Java Generic type is failing without an intermediate variable

java,generics,compilation
I'm having an unexpected error while compiling this example code (in the fails() method). IntelliJ used to not report the error in the IDE, but it has since started to report it (some of the classes were in a library, which seemed to confuse it) public class Main { //...

Define generic function type

generics,inheritance,anonymous-function,nim
Given the following snippet: type Base = object of RootObj Consume*[T: Base] = proc(e: T): bool I want to define several types from base and base consumer for it, like this: type BaseOne = object of Base ConsumeOne = Consume[BaseOne] Now, when i create a new ConsumeOne: let co: ConsumeOne...

Why does adding a parameterless constructor to my entity model class work here? What are the implications?

c#,entity-framework,generics,constructor
So I have this office entity class: [Table("office_entity")] public class EFOffice : EFBusinessEntity { [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessName { get; set; } public virtual ICollection<EFEmployee> Employees { get; set; } public EFOffice(Guid id, Guid tenantId, string address, string businessName) {...

Is my understanding of 'type erasure' correct?

java,generics,type-erasure
After some research I have come to know that generics are a compile time type check feature. They are used to ensure that incorrect types are not used and after that additionally the parameterised type information is also removed to avoid unnecessary overhead at runtime. This process of removing the...

Cannot invoke method with argument list of type KeyType in Swift

swift,generics
I am working on custom message dispatcher in Swift. I want to have dispatcher which can: dispatch enums as events or whatever what is Hashable. Every object which implements one protocol might be added as listeners Here is the code: import Foundation protocol EventDispatcherProtocol: class { typealias T: Hashable func...

Spring, Java : Passing Generic object List as return type

java,spring,spring-mvc,generics,casting
I am working on a Spring-MVC application in which depending upon the mode set by the user, I have to return a List of either Object1 or Object2. Ideally, I can create two controller methods and send the List appropriately, but I would like to know is there any way,...

C++ Templates with multiple constraints

c++,templates,generics,constraints
In C# I am used to specify multiple constraints in a generic method or type as shown right here: How do I specify multiple generic type constraints on a single method? Today I started with C++ for the first time and I am unable to find anything useful when googling...

C# generic return with generic type set in the method not in the call

c#,generics
I am trying to setup a method that retrieves data from a database, and based on data in there it will create and hydrate a class with a generic component. public class MyObject<T> where T : BaseMyType { T MyTypedObject { get; set; } } public class MyType1 : BaseMyType...

Getting List type of class from ParameterizedTypeImpl

java,generics,reflection
I have a field of Map I am trying instantiate that looks like this Map<Long, List<MyObj>> The code to convert it is this 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(); }...

Why does this extension method not initialize the returned object?

c#,generics,extension-methods
I wrote a generic Extension helper method to initialize some parameters of a SoapHeader, however it is not updating the returned object. What am I missing? using System.Web.Services.Protocols; public class Header: SoapHeader {} public class WS { public Header securityHeader { get; set; } } public static class SecurityHeaderExtensions {...

Deserializing Generic Types from a ClassLouder class with GSON

java,json,generics,reflection,gson
I´m trying to parse a JSON file using GSON, the problem is that I´m using a Class that it was previously loaded by ClassLoader. File root = new File("./build/classes"); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class<?> loadedClass = Class.forName("events.Source", true,classLoader); // JSON --> Java "Get the actual type"...

Understanding a captured type in Java (symbol '?')

java,generics
What is ?. Is it related to implementation details of the Java compiler or the type is defined in the JLS. For instance, public interface RecipientTypeVisitor<ReturnType> { public ReturnType visit(RecipientSetType t); } public class RecipientSetType extends RecipientType{ public Integer accept(RecipientTypeVisitor<?> visitor){ //Error: return visitor.visit(this); //Cannot convert capture of #1 to...

Java infinitely recursive self referential types

java,generics,recursion,types
I'm trying to create an implementation of Map that takes collections as keys. What do you even call this conundrum? What is the right way to do the class signature? class SubClass <K extends Collection<E>, V> implements Map<K, V> ^^ Is improper syntax, but indicates what I want to do....

How to provide a default typeclass for generic types in Scala?

scala,generics,types,typeclass,type-parameter
In Scala, if you create a typeclass, say the algebraic structure Monoid[T], you can provide many default typeclass implementations for different types that are monoids. Suppose a monoid is defined as: trait Monoid[T] { def op(x: T, y: T): T def id: T } Since Strings under the concatenation operation...

Generic argument 'extends' multiple classes

java,generics
I have a question about generic arguments, this is the code I have: public <T extends Renderable, Box> void setBackBox(T bb) { ... } As you see you can give as parameter bb an object that extends Box & Renderable. But eclipse gives the following waring: 'The type parameter Box...

C# generic classes inheritance compile time error

c#,generics
I have the following code: public class EntitySchema { } public class ContactEntitySchema : EntitySchema { } public class ProductEntitySchema : EntitySchema { } public class Entity<TEntitySchema> where TEntitySchema : EntitySchema { public string Id { get; set; } } public class Contact : Entity<ContactEntitySchema> { public string FirstName {...

Combining a few methods into the only one. Generics

java,generics,refactoring
I have some code to figure out the correctness of manipulations on different data types (int, long, double) comparing to BigInteger. The manipulation is getting a factorial of a number until the result is the same as BigInteger has. The question is how could i change my code, make more...

How can I pass N number of generic arguments to a typedef function pointer?

c++,generics,typedef
I have this typedef function pointer plot: typedef void(*plot)(); How can I pass a generic argument to it (Something like this): template<typename T> typedef void(*plot)(T); And then, how can I pass N number of generic arguments to it? template<typename T> typedef void(*plot)(T ...); ...

How can I find out the Objective-C generics type?

ios,objective-c,xcode,generics
Xcode 7 contains an Objective-C variant, where you can define a type-hint for (homogenous) NSArray return values and properties, defined such as NSArray<UIImage*>. I'd like to use this feature to rewrite my JSON-deserializer class (which needs such kind of type hints – previously I have solved this by adding a -(Class)jsonHintForKey:(NSString*)key...

Using a Type Variable in a Generic

swift,generics
I have this question except for Swift. How do I use a Type variable in a generic? I tried this: func intType() -> Int.Type { return Int.self } func test() { var t = self.intType() var arr = Array<t>() // Error: "'t' is not a type". Uh... yeah, it is....

Why is generic of a return type erased when there is an unchecked conversion of a method parameter in Java 8?

java,generics,java-8
Consider the following code sample: import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List list = new ArrayList<Integer>(); String response = getProducer(list).get(); } static Producer<String> getProducer(List<Integer> list) { return new Producer<String>(); } } class Producer<T> { T get() { return null; } } When...

Can't figure out how to instantiate generic class returned from function with condition like

java,android,generics,android-studio,java-generics
Can't figure out how to get this work: //Have a tiny CustomServiceLoader implementation public class MyServiceLoader { static private Map<Class<?>, Class<?>> CONTENTS = new HashMap<>(); static public <S, T extends S> void registerClassForInterface(Class<T> c, Class<S> i) { if (c == null) { CONTENTS.remove(i); } else { CONTENTS.put(c, i); } }...

C# generics, cross referencing classes for state pattern

c#,generics
I am trying to get into C# generics and have created a state machine with the state pattern and now I try to refactor. I have a state, which has a reference to the object it's working on. public abstract class AbstractState<T> where T : StatefulObject { protected T statefulObject;...

Create general method to fit interface and general parent class

java,generics,reflection
I have the following method: private void setFilledAndAdd(Shape obj, Color col, int x, int y) { obj.setFilled(true); // needs interface Fillable obj.setFillColor(col); add(obj, x, y); // needs children of Shape (or Shape itself) } If I add one of the lines: setFilledAndAdd(oval, color, x, y); Compile time error apears in...

Grabbing, storing and using all interfaces in the solution, when the interfaces are

c#,generics
Stumped on this one. I had this method: private static List<IBiscuitTransformer> GetBiscuitTransformers() { var type = typeof(IBiscuitTransformer); var transformers = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes().Where(c => !c.IsInterface)) .Where(p => type.IsAssignableFrom(p)) .Select(c => (IBiscuitTransformer)Activator.CreateInstance(c)) .ToList(); return transformers; } This worked great. I had several implementations of BiscuitTransformer, and all was biscuity goodness....

Collection of key-value pairs where only key type is known

c#,generics,icollection,keyvaluepair
I want a collection class of key-value pairs, where ill know the key type at instantiation level but ill only know the value type when adding a new element to the collection. Consider a the code snippet below public class Collection<TKey> where TKey : class { public ICollection<KeyValuePair<TKey, IValue>> Col...

Java Generics - Redundant Type Initialization [duplicate]

java,generics
This question already has an answer here: What is the point of the diamond operator in Java 7? 7 answers I couldn't find an answer to this exact question anywhere else, but I apologize if it's a duplicate. I usually see generic initialization done like this, with the type...

Generic method to perform a map-reduce operation. (Java-8)

java,function,generics,java-8,overloading
How to overload a Function with generic parameter in Java 8? public class Test<T> { List<T> list = new ArrayList<>(); public int sum(Function<T, Integer> function) { return list.stream().map(function).reduce(Integer::sum).get(); } public double sum(Function<T, Double> function) { return list.stream().map(function).reduce(Double::sum).get(); } } Error: java: name clash: sum(java.util.function.Function<T,java.lang.Double>) and sum(java.util.function.Function<T,java.lang.Integer>) have the same erasure...

Test if a list contains element of specific type in Swift

ios,swift,generics
I'm currently trying to write some code that checks to see a list contains an element of a given type T, and am running into trouble. Essentially, this list contains a multitude of elements of different types - however, each of those types are subclassed from one parent type. I've...

Why use a wild card capture helper method?

java,generics,wildcard
Referring to : Wildcard Capture Helper Methods It says to create a helper method to capture the wild card. public void foo(List<?> i) { fooHelper(i); } private <T> void fooHelper(List<T> l) { l.set(0, l.get(0)); } Just using this function below alone doesn't produce any compilation errors, and seems to work...

Set only second argument type in generic method

c#,.net,generics,clr
I have to create a method for selecting a firts property from collection with the specified type. I have created the method like this (I have removed some parts for the brevity): public static IQueryable<TResult> SelectFirstPropertyWithType<T, TResult>(this IQueryable<T> source) { // Get the first property which has the TResult type...

Spark Scala generic min() function

scala,generics,apache-spark
How can I create a generic min() function in Spark which returns a value of the same type as the generic used? Here's what I have for doubles and strings: def minDouble(rdd: RDD[Map[String, String]], field: String): Double = { rdd.map(row => row(field).toDouble).min() } def minString(rdd: RDD[Map[String, String]], field: String): String...

Scala generics: specializing a method

scala,generics
In Haskell I can define a generic type for a tree as: type Tree t = Leaf t | Node (Tree t) (Tree t) If I want to define a function for a specific parameterization of Tree, I can simply do: -- Signature of a function that takes a tree...

Creating a view of multiple Maps' entrySets

java,generics
I have an Iterable<Map<? extends K, ? extends V>> and I'd like to provide a view into the union of these maps' entry sets, i.e. Set<Map.Entry<K, V>>. I can construct a new Set like so (the cast triggers an unchecked warning, but does compile): ImmutableSet.Builder<Map.Entry<K, V>> builder = ImmutableSet.builder(); for(Map<?...

Why can a raw type reference refer to a generic instance? [duplicate]

java,generics,reference,generic-collections,raw-types
This question already has an answer here: Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic? 8 answers Please help understand why Map map1 = new HashMap<String,String>(); // This compiles Map<Object,Object> map2 = new HashMap<String,String>(); // This does not. As per my understanding Map map1 is...

Java generics: Bound mismatch: The type is not a valid substitute for the bounded parameter of the type

java,eclipse,generics
I am facing the following problem: I have these class & interface definitions public abstract class ViewModelRefreshPostListFragment<T extends IRefreshPostViewCallback, R extends RefreshPostViewModel<T>> extends RefreshPostListFragment implements IRefreshPostView { private final ViewModelHelper<T, R> mViewModeHelper = //error here new ViewModelHelper<>(); ... } public abstract class RefreshPostViewModel<R1 extends IRefreshPostViewCallback> extends AbstractViewModel<IRefreshPostViewCallback> {} public...

Disallowed generic array creation in Java

java,arrays,generics
I thought I understood that you could not create arrays of generic classes in Java but a few examples I have seen lately have really confused me. Can someone explain? Thanks! I have a generic class defined as: public class Bag<Item> implements Iterable<Item> Now in a class called EdgeWeightedGraph (below),...

Is there a generic way to negate a decltype condition with SFINAE?

c++,templates,c++11,generics,sfinae
I have a dozen functions or so that take two parameters: a generic, and a specific type. E.g.: template <class A, class B> void foo(A& a, B& b) { cout << "generic fallback" << endl; } template <class A> void foo(A& a, int &i) { cout << "generic int" <<...

Why is my Rigidbody != null immediately after seeing that it is null?

c#,generics,unity3d,null
I am checking to see if "My Game Object" has a Rigidbody. It does not. But the conditional for the null check on Rigidbody fails, despite having just been proven null. Why is this happening? How can I make my condition block run? using UnityEngine; using System.Collections; public class NullChecker...

Java template function

java,generics
I have a function that sometimes has to return a Date other times a DateTime (Joda-Time). static public <T extends Object> T convertTimeForServer(DateTime toSave) { DateTime temp = null; try { temp = toSave.withZone(DateTimeZone.forID(getServerTimeZone())); } catch (Exception e) { } T toReturn = null; if (toReturn.getClass().equals(temp)) { return (T) temp;//Return...

Comparing Generics that are comparable in Java

java,generics,compare,comparable
I have a Generic Binary Tree that will add objects lessThan or equalTo to the left, and objects greater than to the right. My problem is with the comparing the Generics, I know the data value will be a object-wrapped primitive or a String, so they are comparable. But, I...

Resolving Interface with generic type constraint with Castle Windsor

c#,generics,castle-windsor
Given the interface where FooRequest and FooResponse are abstract: public interface IFooHandler<TRequest, TResponse> where TRequest : FooRequest where TResponse : FooResponse { TResponse CheckFoo(TRequest request); } An implementation of: public class MyFooHandler : IFooHandler<MyFooRequest, MyFooResponse> { public MyFooResponse CheckFoo(MyFooRequest request) { /* check for foos */ } } How would...

Vector : References to generic type Vector should be parameterized

jsp,generics,vector
I have this problem(yellow line) in my jsp file which often caused my eclipse program keep no responding. Although my program can run, but how can i get a rid of this following line of code. Vector vFieldName = (Vector) session.getAttribute("table_vFieldName_"+TABLE_TYPE); Vector vTable = session.getAttribute("table_vTable_"+TABLE_TYPE) == null ? new Vector():...

Can I pass type parameters to a testcase in DUnitx?

unit-testing,delphi,generics,dunitx
I'm writing testcases for my FastCode project. I've written a generic tester like so: TTest<T> = record private class var Def: System.Generics.Defaults.IComparer<T>; class var F: FastDefaults.TComparison<T>; strict private class function Slow(const Left, Right: T): integer; static; class function Fast(const Left, Right: T): integer; static; class constructor Init; public class procedure...

Creating an extension method to wrap types as IEnumerables

c#,generics,extension-methods,ienumerable
I wanted to create an extension method that would efficiently wrap single objects as IEnumerables. This was to avoid the cases where you end up putting a new [] {} in the middle of an expression. This is easy enough to do using the following method: public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this...

Implicit Reference Conversion Compliation Error with Generic Base class

c#,generics,covariance
I would like to be able to create the following class structure: public class Person { public Person() { } public string Name { get; set; } } class Student : Person { } class FireFighter : Person { } class PoliceOfficer : Person { } class Building<T> where T...

Confused about the following 'generics' code

java,generics
I can't seem to fully understand the following statement. <T> T[] toArray( T[] a ); Although, I understand that the above statement is the declaration of a function that should be able to accept and return an array of T type objects... I do not understand why 1 - The...

Type error when when trying to override a generic function in a concrete implementation of an abstract class

scala,generics,abstract
The error can be reproduced in the console with the following code. case class SomeClass(name: String) abstract class Factory() { protected def create[U](name: String) : U } class SomeFactory extends Factory() { override def create[SomeClass](name: String) = SomeClass(name) } <console>:11: error: type mismatch; found : SomeClass(in object $iw) required: SomeClass(in...

How do I get a generic class's method that returns T to return it as Integer when T is integer?

java,generics
First of all, sorry for asking such a vague question, I did not know how else to put it. If I have a class Heap: public class Heap<T> { private T[] arr; private int heapSize; public T peek() { if (heapSize > 0) { return arr[0]; } else { return...

Generic method only compiles with one argument

java,generics
The below code will not compile, it says that the method is not applicable for the arguments. The interesting thing is that if I remove one of the arguments (doesn't matter which) then it compiles fine. public class Test1 { static Collection<? extends Shape> someColl = new ArrayList<Shape>(); public static...

When I try to map the properties for an entity (Entity Framework), I get the error the type '__' must be a non-nullable value type

c#,entity-framework,generics,mapping,nullable
My mapping class looks like the following: public class EmployeeMap : EntityTypeConfiguration<EFEmployee> { public EmployeeMap() { HasKey(t => t.Id); Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(t => t.HireDate).IsRequired(); //Property(t => t.JobTitle).IsRequired(); Property(t => t.Salary).IsRequired(); //Property(t => t.Certifications).IsRequired(); Property(t => t.VacationTime).IsRequired(); Property(t => t.SickTime).IsRequired(); //Property(t =>...

How can I call this generic function?

swift,generics,protocols,type-inference
I just thought of this trying to figure out Swift generics. I have come up with the following test code where I'd like to call f(). I can't figure out how I can tell the compiler that the T is Classy in this case. protocol Prot { func doSomething() static...

Java Generic Map with Generic Type as key/ values

java,generics,collections
I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it. Below is the code that I have tried so far. This code as two...

I am getting a The type or namespace name 'listcolumns' could not be found (are you missing a using directive or an assembly reference?)

generics,sharepoint-2010,.net-3.5
Ok, so I have this code which keeps tossing the error above. I am really pulling my hair out trying to figure it out. using System; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Collections.Generic; using System.Collections; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; namespace VarianceList.WebPart1 { [ToolboxItemAttribute(false)] public class...

Why does the Java equals(Object O) method not have a variant which can take a specific object type (e.g. String, Integer, etc) as input?

java,generics,equality,string-comparison,method-signature
I come across problems where I need to compare two strings (or any other object ) for equality/non-equality using Java language. There are two methods on String Object very useful for this purpose viz. compareTo(Object O), which returns a integer result of comparison while other equals(Object o), which returns a...

How are the generic functions and types stored in an rlib?

generics,rust
In C++, the templates can not be generated into dynamic libraries, we can only use them by header files. In C#, generic functions and types can be interpreted by intermediate language in .NET. Rust has no virtual machine, and the generics can be stored in the rlib files. How does...

How to compose two lambdas of type “delegate” in c#

c#,.net,generics,lambda
Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

unchecked call to … as member of the raw type

java,generics,compiler-warnings,unchecked
I am getting the compiler warning: warning: [unchecked] unchecked call to setView(V) as a member of the raw type AbstractPresenter this.presenter.setView(this); where V is a type-variable: V extends AbstractView declared in class AbstractPresenter The code of the AbstractPresenter Class is the following: public abstract class AbstractPresenter<V extends AbstractView, M> implements...

C# pass generic type as a generic type parameter?

c#,generics,ienumerable
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T> { return list.Skip (count).Concat(list.Take(count)); } I want to achive something like this, where T is a type paramter to IEnumerable, and C implements IEnumerable. This is the syntax I came up with but it does not pass the...

Generic TypeCode Type Checking?

c#,generics
Should I avoid type checking with generics? Not using traditional type checking comparisons(myvar is int), but rather using the type's typecode. Using generics, with type checking allows you to create a single method without parameters that supports the tasks of regular overloaded methods. This is a problem with parameter-less methods,...

Why can't we capture wildcards for the method with two parameters?

java,generics,wildcard
Related to that question. I know about wildcard capturing. For instance, the following could be used for reversing a list: public static void reverse(List<?> list) { rev(list); } //capturing the wildcard private static <T> void rev(List<T> list) { List<T> tmp = new ArrayList<T>(list); for (int i = 0; i <...

Why does this method call fail? (Generics & wildcards)

java,generics,extends
I am getting the below error: 'call(ContainsMonitor)' cannot invoke 'call(? extends webscout.Monitor)' in 'WebScoutCallable' Monitor.java WebScoutCallable<? extends Monitor> handler; public setCallable(WebScoutCallable<? extends Monitor> callable) { this.handler = callable; } WebScoutCallable.java public interface WebScoutCallable<T extends Monitor> { public void call(T caller); } ContainsMonitor.java public class ContainsMonitor extends Monitor { public void...

Writing a generic method and the compiler expects T to be a known type [duplicate]

c#,generics
This question already has an answer here: Cannot create a generic method: “T” not found 1 answer I am writing a generic extension method. The compiler does not accept my generic parameter. The compiler message is The type or namespace name 'T' could not be found (are you missing...

Instantiate generic c# List when the reflected type itself is a List

c#,asp.net,list,generics,reflection
I have a reflected Type, which ends up being a List<Type>. So I have: Type modelType = GetMyType(); So - modelType could be List<ClassA> or List<ClassB>, etc. depending on the situation. How do I create this type, and then populate it? I know I can do this: var myList =...

Scala generic cast from String function

scala,generics,casting
How can I write a function to convert a String to a generic type (Double, Int, Float, etc.)? Here's pseudocode for the functionality I'm looking for: def castFromString[A: Manifest](value: String): A = { if (A == Double) { parseDouble(value) } else if (A == Int) { parseInt(value) } else {...

Make `==` a generic funciton in R

r,generics,s4,equality-operator
I would like to make == a generic function. When I run: setGeneric("=="), the definition does not appear to change: > `==` function (e1, e2) .Primitive("==") > setGeneric("==") [1] "==" > `==` function (e1, e2) .Primitive("==") And when I call setgeneric("`==`"), I get the following error: > setGeneric("`==`") Error in...

How to implement generics with type annotations in F#

generics,f#
I have the following skeleton of code: type MyException<'T> () = inherit Exception() type IMyInterface = abstract member Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> : string -> int type MyClass = interface IMyInterface with member this.Method s = let i = s.IndexOf "a" if...

Cannot implicitly convert type from System.Collection.Generic.IEnumerable.MyClass to MyClass

c#,generics,neo4j,neo4jclient
Following is the code for which the error is being generated: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Neo4jClient; using Neo4jClient.Cypher; namespace ConsoleApplication1 { public class SNode { public int shelfid { get; set; } public int floorid { get; set; } } public class PathsResult<TNode> { public...

How to code a generic Swift class which stores a Generator of the same type

swift,generics
I'm trying to write a class which handles objects of a homogenous type, and I'd like to feed in those objects using an (otherwise arbitrary) Generator of the same type. In essence this: class MyGenericClass<T> { var source : GeneratorType var itemsProcessed = [ T ]() init(source: GeneratorType) { self.source...

Java Generics missunderstanding

java,generics
Why is it that a generic T cannot be used as a return type of class if T extends Class. Example: public class Foo<T extends Bar> { Bar[] array = new Bar[200]; Optional<T> forIndex(int index) { return Optional.ofNullable(array[index]); } } T is required to extend Bar Which means that T...

How to make type safety with generics?

java,generics
I have the class public class ReportItem<ReportType extends Report>{ } and the class public abstract class Report implements Iterable<ReportItem>{ private List<ReportItem<? extends Report> > itemList; public void add(ReportItem<? extends Report> item){ itemList.add(item); } //Some other staff } public class ConcreteReport extends Report{ //Some staff } The thing is the method...

Unity resolving generic event handlers

c#,generics,unity,dependency-resolver
I'm using Unity to register all my domain event handlers like such : public static void RegisterTypes(IUnityContainer container) { container.RegisterType<IDomainEventHandler<ProductCreated>, ProductCreatedHandler>(new PerRequestLifetimeManager()); } My handler looks like this : public class ProductCreatedHandler : IDomainEventHandler<ProductCreated> { public void Handle(ProductCreated domainEvent) { // Handle the event } } My domain event looks...

How to create object/singleton of generic type in Scala?

scala,generics,singleton
In below code, How can I convert EmptyTree to object ( Singleton) ? trait Tree[T] { def contains(num: T): Boolean def inc( num: T ): Tree[T] } class EmptyTree[T <% Ordered[T] ] extends Tree[T] { def contains(num:T):Boolean = false def inc(num:T):Tree[T] = { new DataTree(num, new EmptyTree, new EmptyTree) }...

How to tell Java that two wildcard types are the same?

java,generics,types
I have written a small list sorter that works by using Key objects to extract specific "keys" from objects in comparable form. The sorter then sorts the list in accordance with all the keys in turn. The sorter can sort using any set of keys that work on the given...

Ninject generic type xml binding

c#,xml,generics,ninject
I need to bind generic interface with generic implementation using Ninject.Extensions.Xml. The project is .net mvc project. Is there any way to accomplish this ? The class: public class JsonProvider<T> : IJsonProvider<T> where T: new() { ... } Xml configuration (Not working): <bind service="Base.IJsonProvider, Base" to="Base.JsonProvider, Base" name ="Config"/> ...

Generics: Where T is TypeA OR TypeB

c#,generics
When dealing with generics we can do where T: TypeA, TypeB which means T must be implementing both TypeA and TypeB. But is it possible to use an OR in this expression? For example where T: TypeA || TypeB ? is there anyway to do this?

How to create generic convenience initializer in Swift?

swift,generics
I'm tackling with generics in Swift. I've got extension to NSManagedObject class and wanted to create initializer which is only available for classes which implements some protocol I defined. Now I've got something like below but this is not working and even not compiling. Could you help me make it...

Changing Type at Runtime with GenericTypeArgument

c#,generics
This is what I am trying to get (IList<Foo>)listPropertyInfo.GetValue(item) This is how I get Foo type listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0] This is what I tried but couldn't make it successfully Convert.ChangeType(listPropertyInfo.GetValue(item), IList<listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]>) and also this; ((typeof(IList<>).MakeGenericType(listPropertyInfo.GetValue(item).GetType().GenericTypeArguments.Single())))(listPropertyInfo.GetValue(item)) this is...

Pointer of generic type

c#,pointers,generics
Why is the use of pointers to generic types invalid in C#? int?* is invalid, whereas typeof(int?).MakePointerType() doesn't produce an exception. According to MSDN, a pointer can be of: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool. Any enum type. Any pointer type. Any...

Restrict generic T to specific types

c#,generics
I have the following method: public static IResult<T, String> Validate<T>(this T value) { } // Validate How can I restrict T to be Int16, Int32, Int64, Double and String?...

java codependent/circular generics loop

java,generics,circular
Problem: I have two interfaces (here GenCarry and Gen): public interface GenCarry<T extends Gen> { GenCarry<T> setGen(T gen); } public interface Gen<T extends GenCarry> { void applyOn(T carry); } It works when I ignore the 'rawtypes' Warning, but trying to complete them I don't get too far: GenCarry<T extends Gen<GenCarry<T>>>...

Creating a generic / abstract “DBContext” Class for shared functionality among different DBs

c#,database,generics,inheritance,abstract-class
I am working on a C# project that is pulling data from SQL Server, ODBC data-sources and Oracle Databases at different times. At this point, I have created 3 different classes - Once for each type of DB access. However, I am seeing that 95% of the code is identical...

Reversing a Generic Array using “in situ”

java,arrays,algorithm,generics,reverse
For this generic array I added method reverse() that has to reverse the array without using an additional array of elements and I am trying to perform the reverse “in situ” using only swap operations. But I may have gotten it wrong and if so how can it be reversed...

Should remove(Object) be remove(? super E)

java,generics,collections,super,contravariance
In this answer, I tried to explain why the Collection method add has the signature add(E) while remove is remove(Object). I came up with the idea that the correct signature should be public boolean remove(? super E element) And since this is invalid syntax in Java, they had to stick...

Implementing Domain Event Handler pattern in C# with Simple Injector

c#,generics,inversion-of-control,simple-injector
I am trying to implement the Domain Event pattern in C# using Simple Injector. I have simplified my code to be in one file that can be ran as a console app and have excluded the Simple Injector code to keep things clear for the purpose of this question. The...

Arrays, List and Generics in Java

java,generics
Trying to fully understand Generics in Java, I ran into a problem I couldn't really get around, nor find a specific solution for in the web. I have this method: public <T extends City> void someMethod(List<T[]> objectsList) { List<City[]> myList = (List<City[]>) objectsList; } Just writing this into the compiler...

Java generic class that contains an instance of implementation of generic interface

java,generics,interface,architecture
I am developing an independent, self contained component, that needs domain specific parts to function properly. The part of the idea is to create a generic interface, that will settle the usage of interface's implementation in another part of this component (in my example in class B). I have written...

Reflection on IQueryable OfType<>

c#,entity-framework,generics,reflection
I have a Employees DbSet in my Entity Framework context that can be queried as: IQueryable employees = _context.Employees; The Idea is to execute the below method using Reflection: var result= _context.Employees.OfType<PaidEmployee>() I have extended the Employee object to create an PaidEmployee class. I want to query the context for...

Swift: converting between Arrays of 'Protocol' and Arrays of implementing Class

ios,arrays,swift,generics
Consider a protocol and a class that implements it: protocol MyProtocol { var x: Int { get } } class MyClass : MyProtocol { var x: Int = 5 } I have an array of type [MyClass] and I wish to assign it to a variable of type [MyProtocol]. However,...

Scala: generic method using implicit evidence doesn't compile

scala,generics,types,implicit-conversion
I'm learning Scala by working the exercises from the book "Scala for the Impatient". One question asks: Given a mutable Pair[S, T] class, use a type constraint to define a swap method that can be called if the type parameters are the same. My code: class Pair[T, S](var first: T,...

Swift generic constructor

swift,generics
The questions are embedded in comments as well as here: How can I define a default value for a generic T in parameter list? When copying a parameter in Swift, is it pointers or objects? XCode Beta 7 tells me I can't change "head", as it is a "let", see...

C++ equivalent of using for a java parameter/return type

java,c++,generics,extends
In java, to make a function that returns an object that is the same type as a parameter and extends a certain class, I would type: public <T extends MyClass> T foo(T bar) {...} Is there a C++ equivalent of this? In other words, how do I make a function...

Cannot create a generic method: “T” not found

c#,generics,compiler-errors,ado.net
I am trying to implement a method that returns a generic list (List), but I keep getting this error message: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) This is my method code: public static List<T> doQuery(string query)...

Bound mismatch: The type is not a valid substitute for the bounded parameter

java,oop,generics
I've recently started implementing a few data structures and, well, I am trying to make everything as 'extensible' as possible. public abstract class AbstractNode<E extends Element, U extends AbstractNode<E, U>> { ... } public class BinarySearchTree<Element> extends Tree<Element, Node<Element>> { ... } public class Element implements Cloneable { ... }...

Iterable for both generic and raw type

java,generics,iterable,raw-types
Without using generic types I have the following which works fine: public class OC_GuillotinePacker implements Iterable<OC_GuillotinePacker> { @Override public Iterator<OC_GuillotinePacker> iterator() { // code that returns a new Iterator } } Which allows me to loop like this: for (OC_GuillotinePacker gp : packer) { } I updated my code so...