Questions tagged [generics]

18571 questions
1

votes
2

answer
167

Views

Generic Types and Interfaces Java

Having these classes and interfaces.. public interface Shape; public interface Line extends Shape public interface ShapeCollection< Shape> public class MyClass implements ShapeCollection< Line> List< ShapeCollection< Shape>> shapeCollections = new LinkedList< ShapeCollection< Shape>>(); When I try t...
Diogo Ferreira
1

votes
1

answer
2.2k

Views

Generic JUnit tests

I've got an abstract generic collections class GCollection, and a class that extends that called GStack. To test the implementation I have an abstract JUnit test class, which I extend for each of the GCollection implementations I do: public abstract class GCollectionTest { private GCollection
simont
0

votes
0

answer
5

Views

spark select columns by type

I want to have a function to dynamically select spark Dataframe columns by their datatype. So far, I have created: object StructTypeHelpers { def selectColumnsByType[T
Georg Heiler
1

votes
2

answer
881

Views

Is it possible to use object in web service?

enter code hereI would like to send dynamic type with .asvc web service. I have one class with some properties. I would like to send any kind of object even class in this list. And cast back on client side. I mean I always want to use SysResult type. But sometimes with List, sometimes List Like bel...
serhads
1

votes
3

answer
151

Views

Why do .NET methods sometimes return general types instead of using generics and type constraints?

Consider, for example, the method: public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType); defined in System.Reflection.CustomAttributeExtensions Wouldn't it make more sense to define instead: public static T GetCustomAttribute(this ParameterInfo element, T attrib...
Shmoopy
1

votes
1

answer
690

Views

Use Wildcard Class<?> to retrieve Enum from Class of Enums

I have the following code public interface SomeInterface { } public class TestConstants { public static E getEnumString(Class clazz, String s){ for(E en : EnumSet.allOf(clazz)){ if(en.name().equalsIgnoreCase(s)){ return en; } } return null; } public enum A implements SomeInterface { V1, V2, V3;...
muttonUp
1

votes
3

answer
123

Views

Does Android Java support primitive type parameter for generic types?

Today I was looking at the following piece of Android source code: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/animation/IntArrayEvaluator.java The type is declared as: public class IntArrayEvaluator implements TypeEvaluator My understanding of Java generics...
2

votes
3

answer
35

Views

Calling generic method with constraints using reflection

I use Reflection to retrieve the methodInfo from a generic method: public abstract class BaseIdea {} public class ModuleBaseLogic { public void Sponsor(int id) { // Do something } } public class Caller { protected static MethodInfo GetMethod(Expression expr) { return ((MethodCallExpression)expr....
Ole Albers
7

votes
3

answer
132

Views

Restrict a generic Class parameter to classes that implement Map

I'm trying to write a Map builder. One of the constructors will allow the client to specify the type of Map they wish to build public class MapBuilder { private Map map; /** * Create a Map builder * @param mapType the type of Map to build. This type must support a default constructor * @throws Excep...
Dónal
1

votes
0

answer
11

Views

How to use nested generic types in Scala as method return type

I have a few methods that would like to use a nested generic type as its return type. import scala.language.higherKinds trait DBClient { def execute[T[U]
Aqueel Miqdad
0

votes
0

answer
3

Views

TypeScript: Enforce generic inferred type parameter in function

Is there a way to restrict the run call below to be strict about the type allowed by the type parameters specified to the RequestType? The return type R seems to work, but RQ isn't strict. class RequestType { constructor(public readonly method: string) { } } interface FooRequest { foo: string; bar:...
Eric Amodio
1

votes
2

answer
1.3k

Views

Generic Method Using BitConverter.GetBytes

I'm trying to get the bytes for different objects of different types using BitConverter.GetBytes. In order to do this, I'd like to write a generic extension method, rather than write individual extension methods for every type I want to work with (short, long, ulong, etc). Is this possible? Here's t...
Aaron Thomas
1

votes
1

answer
170

Views

What is the reason for using single-character generic type names in java?

In java most (or all?) generic classes in the JDK have single-digit generic type names. For example HashMap's definition looks like this: public class HashMap extends AbstractMap implements Map, Cloneable, Serializable { Why is this the convention instead of more descriptive type names like HashMap...
Adam Arold
1

votes
2

answer
338

Views

Generic function to sort array of class by properties

I want to create a generic function to sort an array of classes based on a property passed. For example, I have these classes public class Car { var id: Int var manufacturer: String var variant: String init(id: Int, manufacturer: String, variant: String) { self.id = id self.manufacturer = manufactur...
avrospirit
2

votes
1

answer
25

Views

Usage of class clause in generic type restriction when restriction alredy contains interface

I think I know why but it would be much appreciated if someone could enlighten me as to why, when I write this method where IStoreable is an interface: public bool TryRetrieveItem(string itemKey, out T item) where T : IStoreable { item = default(T); if (this.RetrieveItem(itemKey, out IStoreable retI...
IsThisAnHuman
0

votes
2

answer
22

Views

Java generic return generic list of type of parameter

I'd like to create the following: //infer the type from parameter but restrict it to one of // Proxy's subtype. return a list of this sub type public static List process( proxy) { return new ArrayList(); //just for example } Usage: List list = process(new ConcreteTypeOfProxy()); The above example ha...
Cybermonk
11

votes
2

answer
199

Views

Why does this code fail to compile, citing type inference as the cause?

Here's a minimal example of the code I'm working with: public class Temp { enum SomeEnum {} private static final Map TEST = new EnumMap( Arrays.stream(SomeEnum.values()) .collect(Collectors.toMap(t -> t, a -> ""))); } The compiler output is: Temp.java:27: error: cannot infer type arguments for EnumM...
tterrag
1

votes
2

answer
326

Views

How can I specify a generic type on an overloaded operator in Kotlin?

I'm looking to overload the division operator, "/", but would like to allow for a generic type to be specified to guide the type of the return value. Here's an example: inline operator fun MyType.div(fieldName: String): T { val value = someFunction(fieldName) return convertToExpectedValue(value) }...
cmorriss
0

votes
0

answer
27

Views

How to reduce code with generics and probably reflection

I have DTO objects, then I need to sort the collection of objects dynamically, kind of like a database ORDER BY, but I do not have a database to actually make the queries do the actual work (I know, but it is what I have today...). It seems to me that the StatusComparator and TypeComparator should...
Schenz
0

votes
1

answer
37

Views

iterating through generic type T if T is IEnumerable without cast

The following code would compile if foo is casted to either a type implementing IEnumerable or dynamic. Is there a way to achieve the same without casting foo ? I am aware I could do two methods and don't wish to force more constraint to T. interface IDummy {} class FooBar where T : class { void Ba...
Baguette
1

votes
1

answer
79

Views

Typescript Generics: return instance of class parameter

I have a data store and want to create a method to load data from the store. The store contains different types (classes) of data. Let's say my store contains (among other) data of type Author. I want to load author with id 1: const author1 = store.loadById(Author, 1); Now how do I have to use gener...
mvermand
1

votes
2

answer
192

Views

How do you define an array of generics in TypeScript?

Let's say I have a generic interface like the following: interface Transform { transformer: (input: string, arg: ArgType) => string; arg: ArgType; } And then I want to apply an array of these Transform to a string. How do I define this array of Transform such that it validates that is equivalent in...
user1084447
1

votes
2

answer
54

Views

Check that object is one of many types in Kotlin

I have the following classes: sealed class A : BaseType sealed class B : BaseType sealed class C : BaseType ... If I then have a processObject method that looks like this: fun processObject(obj: BaseType): Int { return when(obj) { is A -> 1 is B -> 1 else -> 0 } } I notice that I am now repeating my...
Arnab Datta
1

votes
1

answer
48

Views

PECS For generics in Non Collections

Joshua Bloch came up with the PECS, which says the rule when to use ? extends T and ? super T. If you think about PECS in terms of Collections framework, then it is very straightforward. If you add values to the data structure, use ? super T. If you read from the data structure, use ? extends T. fo...
Fatih Arslan
1

votes
1

answer
50

Views

Java generics upper bounded wildcard restriction

Can someone explain what's the difference between these two snippets of code ? 1) private Collection getAnimal() { return null; } 2) private Collection
Martin Čuka
1

votes
1

answer
39

Views

Scala generics: type mismatch with folding

New to scala. Trying to understand why scala compiler is not happy about the below: sealed trait LinkedList[A] { def fold[B](end: B)(func: (A, B) => B): B = this match { case End() => end case Pair(hd, tl) => func(hd, tl.fold(end)(func)) } def sum: Int = fold[Int](0){(hd, tl) => hd + tl} } final cas...
Pritam
0

votes
0

answer
24

Views

Improving performance of generic conversion from DataRow to T

When querying more than 10k data sets from a MSSQL database our software gets pretty slow (more than 10sec loading time). I digged deeper just to find out that they implemented some Entity-like generic object conversion from DataRow to T by calling the contructor of the target type which accepts a D...
spcial
1

votes
1

answer
1.1k

Views

Calling method with generic type using class name as string [duplicate]

This question already has an answer here: Calling a function from a string in C# 6 answers Having this class : class ClassA{ } and a method with this signature: void MyMethod(); All we use it on this way: MyMethod(); But... exist some chance of call MyMethod having the class name as string?. I.e.:...
Sebastián Guerrero
1

votes
2

answer
135

Views

C++ typecast overloading

Supposed I have a class like this: template class Vector2 { public: Vector2(const T a, const T b) : x(a), x(b) {} T x; T y; } I want to be able to do something like this: const Vector2 d(31.4, 48.2); // note the const!!! Vector2 i = static_cast(d); // i.x == 31 // i.y == 48 I have tried overloading...
Charles
1

votes
1

answer
546

Views

Extending the SequenceType in Swift

I wondered why map() and filter() in SequenceType return both an Array. Actually, I don't think that's necessary. Returning a sequence again feels much more sensible to me. However, I got stuck when trying to add sequential versions. Here's my attempt with map: extension SequenceType { func seqMap(...
obecker
1

votes
2

answer
73

Views

Differences between generic methods in java

Suppose I have this interface: public interface Lookup { public T find(String name); } Are there differences between the following methods? 1) public void process(String name, Lookup table) { System.out.println(table.find(name)); } 2) public void process(String name, T table) { System.out.println(...
Jordan
1

votes
2

answer
1k

Views

Type parameter bounds - Unchecked overriding: return type requires unchecked conversion

How can I get rid of warning Unchecked overriding: return type requires unchecked conversion. Found 'org.example.AAndB', required 'T'. in following code. I try to design an interface (Interface) in such a way that it wouldn't explicitly state return type of method get() (AAndB) but rather enumerate...
czerny
1

votes
1

answer
230

Views

Convert a generic IEnumerable<T> to IEnumerable<KeyValuePair> (C#)

In the following code, I need to explicitly mention CountryId and CountryName but I would like to avoid that and trying to create a generic method. public struct KeyValueStruct { public int Key { get; set; } public string Value { get; set; } } private static IEnumerable ConvertPocoToKeyValueList(IEn...
Coder Absolute
2

votes
2

answer
19

Views

Why do I need to force cast a property to a generic method with the same signature as the property?

This is my code: class GenericClass { let enumProperty = SomeEnum.myValue enum SomeEnum { case myValue } func callOtherClass() { OtherClass.handle(property: enumProperty) // Compile error } } class OtherClass { static func handle(property: GenericClass.SomeEnum) {} } Why do I get the compile error:...
J. Doe
1

votes
3

answer
486

Views

Extending a Collection where the Element type is generic (Swift)

It's simple to extend a Collection type in swift to have a custom function for particular Element types: struct MyStruct { let string: String } extension Set where Element == MyStruct { func getFirstWith(string: String) -> Element? { return filter({ $0.string == string }).first } } But suppose your...
David Coufal
1

votes
2

answer
55

Views

static/non-static innerclass : The type parameter T is hiding the type T

When I use static nested class, I don't get the warning The type parameter T is hiding the type T. However, when I use the non-static nested class I get the warning. public class CustomStack { private class CustomNode{ private T data; private CustomNode next; public CustomNode(T data){ this.data = d...
John Rambo
1

votes
1

answer
121

Views

How do I write a generic Swift extension to deep merge two dictionaries?

I'm trying to write a function to deep merge two dictionaries. By this I mean that when the values for a key in both dictionaries are being merged and those values are both dictionaries, they will be merged instead of one being replaced by the other. Here's what I have: extension Dictionary { public...
Hilton Campbell
1

votes
2

answer
363

Views

How to create instance of generic class passing a method reference in constructor with kotlin

Now that I'm using kotlin as my main programing language I'm trying to simplify Android's Recyclerview implementation logic and I'm stuck at following point: Let's say I have defined the following ViewHolder class, where a click position event is propagated via a method reference in the constructor....
Pablo A. Martínez
1

votes
1

answer
265

Views

Kotlin generics expecting unexpected type

I've defined the following base class with two generic types and using it two levels deep (for lack of a better phrase). Here's my use case. abstract class BasePresenter { var model: M? = null var view: WeakReference? = null fun setM(model: M?): Unit { this.model = model if (setupDone()) { updateVie...
Rafa
1

votes
1

answer
379

Views

How to flatten the generic types declaration in typescript?

Case: A function input a nested generic object, and output flat object like follow: interface Deep { p1: T; p2: T; } type Nested = { [P in keyof T]: Deep; } type Flat = { [P in keyof T]: T[P]?; } function flat(input: T, p: keyof Deep): Flat { const put: any = {} for (let k in input) put[k] = input[k...
kcats

View additional questions