Questions tagged [generics]

Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java and in Swift.

2
votes
0answers
9 views

Java module system: 'provides with' generic interface

I'm experimenting with the Java module system. I'm trying to use the ServiceLoader for generic interfaces. It works but I've got warnings in the module-info. Here is my minimal code module ...
-1
votes
0answers
38 views

How to create a deep copy of a generic array of primitive data types?

I am trying to create a deep copy of a two-dimensional array of types int, double, boolean. This question Write a generic method to copy an array helped me quite a bit (see below). But the problem is ...
2
votes
0answers
25 views

How to handle MongoDB codec error when decoding an inherited generics list of lists in java?

I keep getting the following error when trying to deserialize an object containing a generic List<List<T>>: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec ...
0
votes
2answers
28 views

Typescript | Argument of type '{ username: string; password: string; }' is not assignable to parameter of type 'string'

I have this simple service that takes and endpoint and execute a HTTP_CALL. This is it below: export const updatePassword = (data: { username: string; password: string; }): HttpResponse<string&...
0
votes
0answers
28 views

How to generically validate user's input type for all primitives in C#? [duplicate]

I would like to have only one function that would out some primitive according to user's input. I validated the input's type with 'TryParse', but I didn't manage to make it generically. Is There any ...
0
votes
1answer
30 views

In kotlin how to make a class that map with keys from an Enum

Or to put another way, how to construct an internal EnumMap inside my class, where the EnumMap key types are set from the caller's choice of Enum. I was hoping to have code like: enum MY_FLAGS { ...
-2
votes
0answers
35 views

How to sort and pick the values in the collection object?

My collection object class MyGroup holds 3 values. How to sort and pick the values from the collection object? public class MyGroup { public int RowIndex { get; set; } // Row Index ...
1
vote
2answers
61 views

Bounding Multiple Classes in Java

I am working on an assignment, and required is that I create two generic collections (called ComputerOrder and PartyTrayOrder) of several classes: ComputerPart, Peripheral, and Service, and and of ...
2
votes
0answers
27 views

Kotlin: variadic (auto-infer) type arguments possible?

I understood how basic type inference works in Kotlin, but i wonder if i can only call a function with either all type arguments or none of them, or if i can define variable type arguments somehow; EG:...
6
votes
2answers
71 views

Java constrain parameter to common superclass

Motivation I have an Either<L, R> class, which represents a value of one of two types, or semantically different states. In some cases, it is valuable to operate on it no matter which ...
0
votes
0answers
12 views

How to hide certain serializer fields on urls in django rest?

I made a serializer that could Serialize my model fields, I just made uri by serializerMethod Field which gave me the URL of that particular object, I am using the same serializer for both my list and ...
2
votes
1answer
47 views

Why can’t we read from contravariance type

I’m learning generics in Java, and I am learning Covariance and contravariance. I understood covariance and why can’t we write in to covariance type. But for me contravariance is confusing. I want to ...
1
vote
1answer
37 views

Inferring Nested Generic Parameter and Returning It from Function

I have an IModelDefinition like this: export interface IModelDefinition<MT extends Typegoose, QT> { model: new () => MT; } QT isn't directly used in the interface itself, but it is passed ...
1
vote
1answer
30 views

I have an abstract class w/ 1 setter method - parameter is an object. I want a generic <T> parameter that takes on the type of the class extending it

What I want: Instead of "Object" in "public void insertDog(Object object)" method, I would like a generic that extends the class extending the abstract class "DogKennel." For example, if I create a ...
0
votes
0answers
18 views

Groovy @CompileStatic with bounded generics

The Groovy compiler doesn't seem to like this generic method. @CompileStatic class GroovyMain { enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE } enum Day { SUNDAY,...
5
votes
1answer
73 views

TypeScript: mixed behaviour for function with multiple parameters of same generic type

Given a function which receives two parameters of the same generic type: declare const fn: <T>(t1: T, t2: T) => any; I am trying to reason about the different behaviour TypeScript has when ...
0
votes
0answers
22 views

How to chain setters with an abstract class without an unchecked cast [duplicate]

A very common pattern we use is to use generics to set the return type of setters in an abstract class to allow us to chain setters in the implementation. However, this results in an Unchecked cast in ...
1
vote
0answers
34 views

Swift: Can I have a protocol that inherits from a protocol and constrains it?

Say I have the following protocols: protocol RateableItem { var identifier: String { get } // placeholder. This could be a lot of properties var name: String { get set } var rating: Int { ...
-1
votes
1answer
33 views

Explicit class vs generics on an interface

Let's imagine the following case: We define a couple of VO classes: abstract class A { // some class variables } class B extends A { // more specific class variables } Now, what would be the best ...
0
votes
0answers
27 views

Extracting the type keyof'd in a generic function

Is there any way to extract the T type from a function type of <K extends keyof T>(k: K) => T[K] type T = { a: 'a'; b: 'b' } type Fn = <K extends keyof T>(k: K) => T[K] // This ...
0
votes
0answers
39 views

Using '|' operator in generic method [duplicate]

What I am trying to do is generic method that returns aggregation of selected flag enums. The result I am expecting would be MyEnum.A | MyEnum.C (5). Code I have looks something like this : public ...
2
votes
2answers
65 views

Efficiently Obtain IReadOnlyDictionary<int, Animals> from Dictionary<int, Fleas>

public class Flea : Animals {...} var fleas = new Dictionary<int, Flea>(); public IReadOnlyDictionary<string, Animal> Animals => fleas.ToDictionary(pair => pair.Key, pair => (...
0
votes
2answers
47 views

Is it possible to set the return type of an abstract method to be the same as the class?

I would like to set the return type of my abstract method to be the same as the class, not the type of the abstract class, but the same type as the inheriting class.
0
votes
1answer
11 views

Error putting superclass objects in lower bounded wildcard list

I understand that using a lower bounded wildcard on a list as method parameter should let us put elements of that lower bound and its super types but consider following code: public class ...
0
votes
2answers
43 views

Generic nested type inference works with arity-2 but not with currying

Trying to figure out why the code compiles for nested type inference on method with arity-2 but not with currying. object Test { trait Version object VersionOne extends Version trait ...
2
votes
2answers
28 views

TypeScript not inferring props from React.ComponentType

I have the following function which I want to use to take in a ComponentType and its props in order to allow me to inject those props along with the RouteComponentProps const routeComponentFactory = &...
-1
votes
1answer
69 views

Generic class as property in a nongeneric class

I have a custom GridView and I want to set some rules for showing an error. I would like to do something like that: var grid = new MyGridView(); grid.DataSource = new List<MyClass>(); grid....
0
votes
0answers
33 views

DeserializeObject from Generic Type to Known Type after runtime

I'm calling a third-party API that returns a generic result based on a boolean "Success" field. The result is a known type class based on the result response. I'm doing a very stupid way of ...
1
vote
0answers
54 views

C# activate class with <SomeType>, with a body, dynamically, based on a “type” variable

I was looking around here for the answer to this question, and I found a lot of similar questions Passing just a type as a parameter in C# X is a variable but used like a type when trying to cast ...
-2
votes
1answer
35 views

Homework gone wild : “Cannot create a generic array of AbstractChain<T>” [duplicate]

So this is an exercice given by my teacher. We're creating a SkipList, aka a "LinkedList" with shortcuts. He gave us a class diagram with one interface (AbstractLink) and three class (StartLink and ...
0
votes
1answer
26 views

How to don't allow Type Inference and require a explicit type on method call? [duplicate]

I'm currently building a class with a Pair-Structure. I want to somehow guarantee that each member of the pair has the exact same type. My question goes in the direction of: How type inference work ...
3
votes
1answer
65 views

Using the name of a generic type in a class attribute

I have a generic class which needs to use the name of one of its type arguments in a class attribute. I don't know how to access the class name in that context I've tried using typeof(TMsg).Name but ...
0
votes
1answer
26 views

Typed dataset as generic return type

I have two methods that return a typed dataset. I would like to have only one generic method. private TypedDataSet GetData(string query, string tblName) { string conString = .... ; ...
2
votes
1answer
36 views

How can I call parent class overloaded function from derived class instance?

I have a base class with an implemented function and a pure virtual function which share a name, but not arguments. I can't call the function implemented in the base class from an instance of the ...
-2
votes
2answers
24 views

Using reflection to cast an object to List of custom type

I have following scenario: I have compound object which includes lists in it, I want to pass a 'path' to it like - Result.CustomerList.Name Result is an object that contains List of Customer, but ...
-2
votes
0answers
31 views

Why is applying reduce on this stream of objects results a compilation error and how to fix it? [duplicate]

I have a simple Gradle project: plugins { id 'java' id 'application' } repositories { mavenCentral() } sourceCompatibility = '11' targetCompatibility = '11' mainClassName = 'demo.Main' ...
4
votes
1answer
87 views

How to look into generic tList during Delphi debugging

I use Delphi 10.3.1 COMMUNITY version and can't look into generic tList while I debug the project. I know the latest version of Delphi doesn't support the old-typed debug feature which allows to look ...
0
votes
0answers
28 views

Expression conversion error using generic repository on MongoDB

i'm having some trouble on making a generic mongodb repository (i've collection made as GenericRepositoryEntry) public static void SaveRepositoryEntry<TDataObject>( TDataObject msg, ...
3
votes
1answer
45 views

Why is the Java compiler losing track of generic types in constructor instantiation? [duplicate]

Given a generic class Test<T> and a constructor that takes the Class of the generic parameter public Test(Class<T> clazz){} Why doesn't the compiler correctly infer that generic type on ...
0
votes
1answer
31 views

Decode struct with generic array property

I have a following struct with generics for API response with pagination: struct Paginable<Body> { let data: [Body] let meta: Meta } extension Paginable { struct Meta: Codable { ...
0
votes
1answer
25 views

Simple Generic Function in Kotlin Fails

Here's a simple generic function in Kotlin: fun <T> twice(x: T) : T { return 2 * x } Attempting to build this (either in a project or REPL) results in the following errors: error: none of the ...
0
votes
1answer
28 views

Calling delegate method from generic class

I would like to call MyDelegateMethod from SomeClass but I have no idea how to do it. I want my class to work for every delegate not juste only the one provided in the sample code. thanks ! using ...
11
votes
3answers
780 views

How to make method return the same generic as the input?

I want to split a string delimited by commas and use the result as either a Seq or a Set: def splitByComma(commaDelimited: String): Array[String] = commaDelimited.trim.split(',') def ...
0
votes
1answer
22 views

how to make asynchronous static method with same generic array param and same generic array return type

I want to do all of the same code twice, but just for two different objects. I am getting these objects from a SOAP API (rather outdated one). I want to avoid writing duplicate code over and over ...
0
votes
0answers
24 views

Constructor called with generic type always picks parent type while more specific constructor exists [duplicate]

In the below code, I have re-produced a C# behavior that I ran into and can't understand. The idea is: A generic class with a type constraint (Parent here) has a method that returns T which can be, ...
0
votes
1answer
32 views

generic that extends multiple classes in java [duplicate]

I have Two classes: User and UserDto. They are similar, like: User { int id; get\set} UserDto{ int id; get\set} And i have a method lets call it doSmth(). Is there a way to make this method work ...
1
vote
1answer
71 views

Is it possible in Java to forbid certain superclasses in generics?

I would like to ask if it is possible in Java 8+ to declare a generic bound T so that it extends superclass/superinterface U (which could be Object, or Serializable) but breaks compilation if T ...
0
votes
1answer
7 views

Parameter of any type that extends another type in TypeScript?

I'm creating an HTML5 game with TypeScript, and I want to render all children of a GameObject automatically. But there are many different classes that can extend GameObject class. What I ideally want ...
0
votes
1answer
17 views

how to map generics collection with hibernate

i have a wrapper class with a list of generics @Entity public class Rubrique<T> { ... @OneToMany(cascade = CascadeType.ALL, mappedBy = "declaration", fetch = FetchType.LAZY, ...
1
vote
1answer
61 views

Is there a way to generically implement a trait for objects in smart pointers?

Is there a way to generically provide an implementation for a trait for objects in smart pointers (e.g. Box, Rc, etc)? Example: use std::borrow::Borrow; use std::rc::Rc; trait KindaEqual<Rhs = ...