Questions tagged [generics]

22156 questions
1

votes
0

answer
112

Views

Can Java recognize a type parameter, T, as a super type of some class?

Background: I have 3 classes: A, B, C where they all extends 'Super' and implements 'Interface' and I want to write code that only uses only the methods from 'Super' and 'Interface' Unfortunately, I don't have control over the source code of A, B, C, 'Super', 'Interface' to change the inheritance ch...
Sgene9
1

votes
0

answer
87

Views

Mapping generic parameter to compile time data in Typescript?

I'm playing around with trying to disentangle a codebase from Sequelize. Right now we have tons of code like: // Defining interface for model instances interface UserInstance extends Sequelize.Instance { ... database field here ... } // Wrapper class managing connection & model definitions class Db...
Chris Tavares
1

votes
0

answer
55

Views

Unable to Initialize a Generic type with a Generic method parameter

I was fiddling around with generic types in the Swift playgrounds, when I attempted to use the code below: class Node { let value: T init(_ t: T) { self.value = t } func convert(to type: U.Type) -> Node? { guard let new = value as? U else { return nil } return Node(new) } } Note: This code is hypoth...
Caleb Kleveter
1

votes
0

answer
862

Views

Executing MediatR PreProcessor Only for Specific Interface Types (Commands)

[NOTE: This is a 'replacement' question. The first one was based on my main project's code so I've redone the question with code from a single-purpose project that illustrates the principle more cleanly. The question remains the same, just better presented.] The Scenario I'm trying to setup a comman...
platypusjh
1

votes
1

answer
281

Views

Use generic extended swift class in Objective-c

In my project i have many swift classes that extend generic classes. And Now i'm in a need to send data from objective-c class to these swift classes. Is there any possible way to do this ? I have tried using @objc before class as shown below but it didn't allow me to do this. I followed this answer...
Parv Bhasker
1

votes
1

answer
63

Views

How to get the data type in Typescript using Generics

I have a data structure that is built using generics. When I go to populate data though, I want to ensure I can convert some simple formats into the proper types. As the class us configured using Generics, I cannot seem to detect the type of the data in other code. This is a simple example extra...
Steven Scott
1

votes
1

answer
82

Views

Swift 4: generic conforming to AnyObject does not accept a protocol conforming to AnyObject

I need to create an array of type-safe weak references a structure that holds a 'type-safe' weak reference and can be an element of an array: public struct WeakRef: Hashable { public weak var ref: T? public let hashValue: Int init(_ ref: T) { self.ref = ref self.hashValue = ObjectIdentifier(ref).has...
Yaroslav Yaremenko
1

votes
0

answer
44

Views

Why does CodeTypeReference truncate my type with generic parameters?

I'm trying to define a base class of type 'foo' in CodeDom, but it comes out as 'foo
Jason Hernandez
1

votes
2

answer
196

Views

Overriding generic abstract method to return specific type

I have an abstract class that is the below method signature: protected abstract TResponse Handle(T command) In a class that overrides this I have something like the below: protected override TResponse Handle(ListFilmsByIdCommand command) { return 9; } However this fails to compile as it cannot conve...
Jon
1

votes
1

answer
224

Views

Java ambiguous method call with generics

Java generics ambiguous method call in the following example: public class Foo { public void set(Path attribute, X value) { ... } public void set(Path attribute, Expression
Sunnyday
1

votes
2

answer
107

Views

Scala - composing generic types

I want to create a generic interface which hides the implementation of the hash function on the key of a product (which is used to lookup products and for various caching and calculations outside the scope of the product itself). I want to tie the concrete implementation of the hash function to the...
Avner Barr
1

votes
2

answer
50

Views

Use of generics in Exceptions

So my question will sound like a discussion but it's not. I'm looking for sources on the topic but I can't seem to find many. Here I go, in .Net, it is possible to create a generic exception and catch it, ie. class MyException : Exception { } // ... catch(MyException e) { } But I notice that I can't...
Foxtrot Romeo
1

votes
1

answer
83

Views

Unable to override java generic function with scala parameterized type

I am getting the error - Method read has incompatible type ; when I try to override a java generic function name with a Scala parameterized type. This is the java abstract function I am trying to override. public abstract class SRType{ //Other abstract functions public abstract T read()throws IOEx...
Pratyush Das
1

votes
0

answer
351

Views

Jackson ObjectMapper throwing java.lang.ClassCastException: java.util.LinkedHashMap while deserializing generic type

I am trying to deserialize an Custom Generic Type class using Jackson ObjectMapper, but the test is throwing the following exception.I know the jackson api is not able to find the correct construct type, but i don't know what is the correct constrct type in my scenario. I tried with constructCollect...
sunish jose
1

votes
1

answer
42

Views

Java won't accept parameter of Map<String, MyClass> when the method signature is Map<String, IMyInterface> and MyClass implements IMyInterface [duplicate]

This question already has an answer here: Is List a subclass of List? Why are Java generics not implicitly polymorphic? 16 answers What is PECS (Producer Extends Consumer Super)? 12 answers I am getting the error: Error:(6356, 38) java: incompatible types: java.util.Map cannot be converted to java...
David Thielen
1

votes
2

answer
57

Views

Java Generics: using parameterized interface in method calls

I want to store a function to be applied to any instance of a class. As I want to do this for different classes, I am using an interface in my storing and applying code. But I have some problems with my type variables: I've got an interface public interface SomeInterface And an implementing class p...
Agast
1

votes
1

answer
94

Views

How to Implement generics in database insert?

I can't come up with proper title of that question. If someone think he can give a better name he is free to change it. I have the following piece of code: string xmlFilePath = pathFromserverFolder + '/articles.xml'; XmlSerializer deserializer = new XmlSerializer(typeof(Articles)); TextReader textRe...
Profile3ForStack
1

votes
0

answer
49

Views

Java generics and reflection to create and set model for SimpleJdbcCall in Spring

I am trying to use reflection and generics to create models using SimpleJdbcCall. At the moment I have to create a distinct mapper per model that I add to the project. I would like to create a mapper that uses reflection to just simply map the model, so that I only have to write one mapper (in the m...
resu
1

votes
0

answer
394

Views

C++ error: request for member … which is of non-class type

I've tried looking at other similar questions, but they all seem to contain answers regarding a feature of c11 I'm using. When running the following code I get the error: error: request for member 'current' in '((mtm::MtmSet)this)->mtm::MtmSet::it.mtm::MtmSet::iterator::operator->()', which is of no...
Osmosis Johns
1

votes
1

answer
329

Views

Swift Declare generic type that conforms to a certain protocol in a dictionary [duplicate]

This question already has an answer here: Store Encodables in a Swift Dictionary 2 answers I am using this function public mutating func encodeIfPresent(_ value: T?, forKey key: KeyedEncodingContainer.Key) throws where T : Encodable to encode a entity But my entity contains a dictionary which I al...
Wstunes
1

votes
1

answer
48

Views

How allow base auto configuration class? When I have two that extend it, only the first one gets called

I have a base auto configuration class that uses generics to create the bean you want. But when I test having two configs that both extend that base config class, the second one never creates its beans. I believe this is because the method name is the same on both, so Spring assumes that it's alread...
Don Rhummy
1

votes
0

answer
426

Views

Cannot parse Json to data class using kotlinx.serialization

In an Android project, I am trying to parse a Json response from a remote endpoint using kotlinx.serialization and Retrofit. I am using Jake Warthon's https://github.com/JakeWharton/retrofit2-kotlinx-serialization-converter to set the converter when setting up the retrofit instance Retrofit.Builder(...
Nicolás González
1

votes
2

answer
78

Views

How do I create a delegate for a property getter from an open generic type

I have a PropertyInfo for a property on an open generic type, obtained in the following way: public interface ITest { T Item { get; } } var propertyInfo = typeof(ITest).GetProperty('Item'); I'd like to be able to create a concrete, callable delegate, filling in the class type parameter (e.g. Func) f...
Philip C
1

votes
1

answer
102

Views
1

votes
3

answer
401

Views

iOS swift Alamofire parsing, creating generic class to parse json data

I have this JSON data to parse : { 'data': { 'user_name': 'JohP llDoe', 'email_address': '[email protected]' }, 'result': { 'code': 0 } } The data type change from a web-service to another, but the general structure is always the same. So I create this general Class using EVReflection to parse the Da...
user1485365
1

votes
1

answer
36

Views

Can you make `table` behave as it was a generic function?

Suppose I have an object x from class foo (representing some intervals): x
Qaswed
1

votes
1

answer
46

Views

Can't infer embedded type arguments from type

I came from the c++ corner and have some unterstanding issues with c# generics. Questions: Why does the following code not working? Do you have some links for me to improve my generic knowledge? Definitions public abstract class Item{} public abstract class ParentItem : Item where T : Item{ public...
Syrlia
1

votes
0

answer
54

Views

How can I get notified of ProcessBean events for a producer method returning a type X?

A (valid) CDI producer method like this: @Produces public Integer fortyTwo() { return Integer.valueOf(42); } …is not observed by a (valid) portable extension's container lifecycle event observer method that looks like this: private final void processBean(@Observes final ProcessBean event) { /* ?!...
Laird Nelson
1

votes
0

answer
52

Views

Pagination and LazyLoading in EFCore with Generic Repository Pattern

I am using EFCore and Generic Repository Pattern for my project and on my Core layer I have IEntityRepository interface: public interface IEntityRepository where T : class, IEntity, new() { PagedResult GetAll(int pageNumber, int pageSize, Expression filter = null, params Expression[] includeProperti...
Sümeyya Tuğçe Arar
1

votes
0

answer
101

Views

Pass multiple Func Expressions to C# method

The entity framework's DbEntityEntry has a method Collection which accepts lambda expressions to load entities. DbCollectionEntry Collection(Expression navigationProperty) where TElement : class; In my project we are following repository pattern so to call this I have created a method in the reposit...
Rudresha Parameshappa
1

votes
0

answer
53

Views

Swift: How to make a Generic Class conform to a delegate protocol which its method has a Generic Type parameter?

I have a delegate protocol which its method requirement has a Generic Type parameter on it and I have a Generic Class which I want it to conforms to that delegate. The problem is that I can't make that class to satisfy the requirement. protocol ListDelegate: class { func list(_ list: List, didUpdate...
1

votes
1

answer
139

Views

Generic type constraint in variable/field declaration

Suppose we have a generic interface: export interface IKeyValue { key: K; value: V; } Now, we want to declare a variable/field and limit which types could be used as K and V: public items: IKeyValue[]; The code above doesn't compile. I'm using TypeScript 2.6. How can we achieve it in TypeScript?
Alexander Abakumov
1

votes
1

answer
75

Views

Typescript Generic type makes compilation error

I've got a case where i need to get a hierarchy between differents class of items. They all extend the same class ItemExt. I'm using Typescript 2.4.2 Here is my Code : export class ItemCollection { constructor(private typeClass: { new (): ItemSon; }, parent? : ItemFather, fatherColl? : ItemCollectio...
rdecla
1

votes
0

answer
227

Views

Restsharp Doesn't Deserialize Enumeration

I'm trying to call an external RESTful API in my application and I've been using restsharp for it which has been great so far so but I think I've ran into a problem. I'm calling an API which normally returns XML documents like this: 100 OK 52788198 TEST 22802 This is my code: internal class SubmitMe...
Alfredo Gallegos
1

votes
0

answer
92

Views

Generic types constrained to be equal aren't convertible to each other

First off: I'm using the Swift Development Snapshot 2018-02-13 (a), so perhaps that is causing the issue. I am having a problem with Swift's generics. The issue revolves around a type that is generic over two type parameters: struct Graph Value is unconstrained and Edge is constrained to be an EdgeT...
Marcus Rossel
1

votes
1

answer
132

Views

Base service for Custom JPA Data Repository

I've implemented a custom JPA repository as : public class BaseEntity{...} public class DerivedEntity extends BaseEntity{...} @NoRepositoryBean public interface BaseRepository extends JpaRepository{ //some common method } @Repository public interface DerivedRepository extends BaseRepository{ } Now,...
Ankit
1

votes
1

answer
88

Views

Bug in .NET framework, reference hidden member using generics [duplicate]

This question already has an answer here: Hide a base class method in a generic derived class 2 answers I am thinking that there should be a bug in .NET framework as per the specifications 'when we refer object directly instead of using the parent reference it should call the hidden member'. For th...
1

votes
0

answer
146

Views

Kotlin generic issue, should be subtype of Nothing

I'm writing a simple Spring test on Kotlin and have a compilation error with generics that I can't understand. The function is below: @Test fun actuatorRootReturnsOnlyAllowed() { val expectBody:WebTestClient.BodySpec = client!!.get().uri('/app') .accept(MediaType.APPLICATION_JSON_UTF8) .exchange() ....
Yuriy Yunikov
1

votes
0

answer
34

Views

Force output of + operator to be the same as its input in a function? [duplicate]

This question already has an answer here: Matching a generic parameter to an associated type in an impl 3 answers How do I require a generic type implement an operation like Add, Sub, Mul, or Div in a generic function? 2 answers I have a function test that calculates the sum of two variables of ty...
jiwopene
1

votes
1

answer
55

Views

How can I solve my issue relating to parameterless constructor when using generics with constraint defined

I have a class that i try to create dependency injection for in my StartUp.cs file, like this services.AddTransient(); I also try to pass the the IContextFactory into a constructor like this public BlogPostRepository(IContextFactory blogPostContext) but I get errors on the lines above...
ife labolz

View additional questions