Questions tagged [generics]

Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java, Swift, Rust and Go (since 1.18).

generics
Filter by
Sorted by
Tagged with
1 vote
2 answers
1k views

Guava cache generics error

Magical error appears when trying to create guava cache: import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import java.util.concurrent.ConcurrentMap; public ...
user2602807's user avatar
  • 1,262
3 votes
1 answer
804 views

Which language's generics are generic classes and functions in OCaml similar to, C++, Java or C#?

I learned the difference between C++ templates, Java generics and C# generics from https://stackoverflow.com/a/31876747/3284469, which help me better understand how to use them correctly in different ...
user avatar
3 votes
1 answer
1k views

Swift 4 generic, referencing self

I'm considering the following structure using Swift 4: class BaseClass { // abstract function func doSomething<T: BaseClass>(with object: T) {} } class SubClass: BaseClass { var ...
Tack-Gyu Lee's user avatar
-1 votes
2 answers
542 views

cannot implicitly convert type List<Foo> to system.collections.generic.list<T>

I feel like I should really know the answer to this one... LOL!! Why does returning a typed list within a function of generic list raises a compile error? Example Code: public List<T> Method&...
user167698's user avatar
  • 1,843
0 votes
1 answer
66 views

C# how to pass a class as a parameter into a method and determining the base class of the parameter class

So I have been adding a class to a list of classes by calling the constructor in the add method of the list: SupportedTests.Add(new SpecificTestClass27()); However, the classes I'm using are ...
jjumboshrimp's user avatar
1 vote
1 answer
328 views

Why is this generic method not giving compile-time error?

In this program I am creating a generic method in which second parameter extends first parameter but when I am passing String as first paameter and Integer array as second parameter then too the ...
Ankit Srivastava's user avatar
0 votes
1 answer
55 views

How do design a method that can query the DB and return different type that implements the same interface?

Context We are developing a software for our Government, the government releases some PDF's describing an XML file structure and their respective XSD. So, we generate all the POCO classes we will ...
Ewerton's user avatar
  • 4,245
4 votes
1 answer
7k views

Kotlin inheritance with generics

I have an abstract class, let's call it A. abstract class A(private val name: String) { fun read(key: String): Entity { ... } fun write(entity: Entity) { ... } ...
pavlos163's user avatar
  • 2,820
5 votes
3 answers
2k views

Why is specialization in C# generics limited?

The question "What is reification?" has a comment on C#'s generics: Type information is maintained, which allows specialization to an extent, by examining type arguments using reflection. However, ...
user avatar
0 votes
0 answers
219 views

How/where to resolve a generic property type

I ran into this problem. When I adapted my code to that solution, I ran into another issue: I don't know, how/where to resolve the generic type. I ended up, modifying all the classes/structs up to ...
d4Rk's user avatar
  • 6,663
0 votes
1 answer
78 views

Dictionary of different types, where the pulled object must remember its type, best approach?

I'm trying to find the best way to create a dictionary that can hold 6 different sub-types of the abstract Reward type, while also remember the individual item's original sub-type when pulled out ...
K_Nielsen...'s user avatar
4 votes
4 answers
521 views

How to create a type safe factory for generic classes?

[Note: I have looked at all the possible duplicates - none are direct duplicates and none provide an answer to this specific question.] I want to create a factory for event handlers, where the event ...
jimmy_terra's user avatar
  • 1,470
6 votes
1 answer
2k views

Class of a generic Java type cannot be assigned to a variable whose Class type is upper bounded by a generic super type

I use Java 8. In my design a have a few simple classes which model value parameters such as FloatParameter or EnumParameter<E>. A have a common generic super class of these classes (...
Adam Jurčík's user avatar
-1 votes
1 answer
81 views

Create a map of generic list to initialize multiple ComboBox in once

I would like to create a map with the name of the property object as a key and a list of type object as a value. In my case I would like to have a map : Dictionary<string, List<Object1 Or 2&...
Benoît's user avatar
  • 153
0 votes
2 answers
831 views

Passing Self in a static function

I am using migrating from Objective-C with MagicalRecord to Swift with CoreStack (being used as the Core Data framework). And the CoreStack has the following API to fetch a record, something like the ...
Roman Zolin's user avatar
0 votes
3 answers
702 views

When does type checking of generic definitions and instantiations happen in C#?

In C#, does type checking of generic definitions happen at compile time? does type checking of instantiations of generics happen at run time? Thanks. The above questions are for me to understand ...
Tim's user avatar
  • 97.1k
3 votes
1 answer
933 views

Common Equatable class on Swift

I need container for Any Equatable items in NOT Generic class (for example UI classes initial from storyboard). I need like this var items: [Equatable]? but it don't work, Equatable need Generic. ...
EvGeniy Ilyin's user avatar
1 vote
4 answers
208 views

Why cast is needed when returning this from self-bound generic in Java

In this case my IDE shows compilation error in return statement. public class Base<T extends Base>{ public T get(){ return this; } } When I add a typecast as in code bellow ...
Streamline27's user avatar
0 votes
1 answer
622 views

Jackson and generic types inside a subclass

I am rewriting the question since I figured out the actual error in the code. This is a fully functional example of my issue (I am using Jackson 2.9.0): import com.fasterxml.jackson.databind....
hvm2hvm's user avatar
  • 63
2 votes
0 answers
2k views

Typescript: Generic type of function parameter signature

I try to declare a type which defines a transformation of a function type generating a type with the same arguments but another return type. The goal is to write a function createAction which expects ...
remolueoend's user avatar
0 votes
0 answers
293 views

How do I create a new instance of a Generic Class type in a Scala Trait

I have the following... trait SourceTrait[T <: Connector] extends BeforeAndAfterAll{ ... override def beforeAll(): Unit = { super.beforeAll() ds = new T connector = ds.asInstanceOf[...
Jackie's user avatar
  • 22.8k
5 votes
2 answers
3k views

Does TypeScript allow a type alias to specify generics?

I would like to be able to alias a very generic function and specify part of the generic parameters, thus creating a less generic version of the same function. Something like the following: function ...
alloy's user avatar
  • 21k
1 vote
1 answer
860 views

Restrict the usage of method decorators

I have a decorator for methods that I want it to be used only with async methods. This is an example of usage: class A { @deco() // This should work. public async works() { } @deco() // This ...
lilezek's user avatar
  • 7,146
5 votes
1 answer
3k views

Java compilation fail with method reference but works with lambda

We're trying to add an overloaded collect method to our extended Java Stream API which we're currently defining as: interface ExtendedStream<R> extends Stream<R> { <R1> R1 ...
Galder Zamarreño's user avatar
6 votes
1 answer
332 views

How to avoid unchecked casts in a Java Generics extended Comparable interface?

Why is the unsafe cast (T) needed in this generic interface? If T is comparable to itself, i.e. implements ExtendedComparable<super of T> which means also ExtendedComparable<T>, then why ...
ms34449's user avatar
  • 61
3 votes
1 answer
2k views

Generic typealias with Void gives error missing argument in Swift 4

When I tried to migrate to Swift 4 an error occurred with my generic typealias for closures if you give it Void as an input. This worked fine in Swift 3 but not so much now, anybody know why, and is ...
Cenny's user avatar
  • 1,966
4 votes
3 answers
1k views

Using Java and C#'s generics to simulate duck typing

http://nullprogram.com/blog/2014/04/01/ tries to explain that Java's generics can't simulate duck typing with an example: class Caller<T> { final T callee; Caller(T callee) { ...
Tim's user avatar
  • 97.1k
-2 votes
1 answer
431 views

How is specialization of a generic type very restricted in Java generics?

From https://stackoverflow.com/a/31876747 In Java generics, a generic type definition is transformed to essentially one concrete generic type shared across all allowed type argument combinations. ...
Tim's user avatar
  • 97.1k
1 vote
1 answer
198 views

Cannot get interface signature correct when implementing via TypeBuilder and Emit

I have not worked much with dynamic classes and emit and I've been hitting my head against a brick wall trying to work this out. What I want is a helper to use when I am moving structs and other value ...
BruceCo's user avatar
  • 21
1 vote
1 answer
1k views

Scala type inference error

I wrote a combined map-and-find function that applies a function to an Iterable and returns the first mapped result for which a predicate is true: implicit class EnhancedIterable[A, B[X] <: ...
Josh Stone's user avatar
  • 4,388
6 votes
1 answer
9k views

(Swift 3)generic parameter T could not be inferred

I am trying to create a function which takes in nested arrays of objects like [1,[2,[3,4],[5,6]]] and return values in single array like this [1,2,3,4,5,6]. I wanted to do it for generic objects so I ...
Bharath Reddy 's user avatar
0 votes
1 answer
70 views

Typescript: Can I refer to type variables of a type variable?

I have two generic types - Client<T> and MockClient<T>. I would like to describe a third generic type - Mocked<C extends Client> - which should be the specialization of MockClient ...
dgirardi's user avatar
  • 182
-1 votes
1 answer
153 views

How to call a generic method in the driver class

I'm trying to call this method in the driver class with Integers but it doesn't work. Please can anyone help me public SLL<T> missing(SLL<T> testList) { if(this.head == null) { ...
Armee's user avatar
  • 11
0 votes
0 answers
38 views

How can I get Generic injection entities use Class and generic class name in Spring?

I only have two determine the type,one of is my Basic Class, another is generic class name. BasicOrmDao.class; Class cls = Class.forName("com.base.Role"); My injection class is class RoleDao ...
Zheng Xiaodong's user avatar
0 votes
1 answer
89 views

Using inheritance or templates for generic wrapper class

Right now, I'm trying to abstract away the differences between a matrix and a scalar in C++ in terms of construction and operations. For the reference, the LA lib is Eigen. I want something like this ...
OneRaynyDay's user avatar
  • 3,788
2 votes
1 answer
109 views

Restrict generic parameter to protocols inheriting from protocol

I'm not sure what where clause can restrict a generic parameter to be a protocol that inherits from a certain protocol. protocol Edible {} protocol PetFood: Edible {} struct CatFood: PetFood {} ...
andyvn22's user avatar
  • 14.8k
1 vote
1 answer
1k views

Networking Call with Generic Decoding type

I am attempting to create a generic networking function I am looking to make an API handler which will download JSON from the network and convert theme to Swift structs that conform to the Decodable ...
Andrew Walz's user avatar
0 votes
0 answers
24 views

Java Generic Function Return Type [duplicate]

I want to create a collection of actions for specified class types. I was attempting something as follows. Map<Class<?>, Function<String, ?>> mapper = new HashMap<>(); I end ...
cplusplusrat's user avatar
  • 1,435
1 vote
1 answer
375 views

Extract FieldType key and value from HList

I would like to extract the key and value of the head of an HList using these two methods: def getFieldName[K, V](value: FieldType[K, V])(implicit witness: Witness.Aux[K]): K = witness.value def ...
jamborta's user avatar
  • 5,170
1 vote
0 answers
45 views

C#: Can't cast a string to Generic T when T is "String"? [duplicate]

I have the following method which attempts to parse a string into a type T when T provides a parse(string) method: public static bool ParseToType<T>(string s, out T parsedValue) { ...
GGizmos's user avatar
  • 3,605
3 votes
1 answer
95 views

Issue when creating overloads with different number of generic parameters

The original purpose of this simplified code was to create a generic method in typescript that receive a delegate and an object and returns a new delegate whose signature should be the same of the ...
Andrea Pirola's user avatar
3 votes
2 answers
3k views

Is this possible to do using plain BiFunction in method definition

I had the following problem: a method should take in a bi-function that takes 2 arguments - one is of type Collection<T> and the other is T; the actual function could be actually Collection::...
Antti Haapala -- Слава Україні's user avatar
0 votes
2 answers
1k views

Unmarshalling a nested Set using JAXB

Sorry for the long post, thank you in advance! I need to unmarshall this XML: <RootTag> <Container type="type1"> <value name="name1"/> <value name="name2"/> </...
Sam's user avatar
  • 1,942
7 votes
1 answer
252 views

Generic messages in message-based architecture

I am experimenting with message-based architecture in Swift. I am trying to do something similar to the Elm Architecture, for example. This is how my code looks: enum SideEffect<Message> { ...
zoul's user avatar
  • 103k
0 votes
1 answer
53 views

Passing a non-static method to a Generic Function

I have a header file where one of the functions is: template <class Pclass, class Pfunc1, class Pfunc2> //Capable of multiple outputs per call int view_recordT(Pclass Object_1, char ...
user avatar
5 votes
1 answer
588 views

Swift generic function call underlying method based on generic type

I am writing an interface to Someone Else's Code (SEC), and I have a long list of functions more or less like this: public func readString(_ row: Row, columnName: String) -> String? { return ...
Jerry's user avatar
  • 3,506
1 vote
1 answer
133 views

Generate Shapeless Record from Generics

I have this standard Shapeless code: case class KeyValue(key: String, value: Int) val kv = KeyValue("key", 1) def processCaseClass(p: KeyValue) = { val gen = LabelledGeneric[KeyValue] gen....
jamborta's user avatar
  • 5,170
0 votes
1 answer
128 views

Java Generics, detecting out of range bytes

I'm trying to better understand Java Generics so I put together a small method which takes in a number (a Generic type that extends Number) and simply displays it back. So what happens is that if the ...
Zippy's user avatar
  • 3,858
0 votes
2 answers
71 views

Java Method using generic parameter?

I am new to Java and writing a method for a generic Linked List that accepts another Linked List as a parameter. As I understand, this new Linked List should be of the same type as the Linked List ...
user8584662's user avatar

1
377 378
379
380 381
1023