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).
49,362
questions
0
votes
0
answers
25
views
Template of microservice json rpc in Rust
I recently decided to migrate a typescript application and told myself "Why not in Rust ?, Let's do it in Rust then ..."
As my application is a suite of microservices which are of the same ...
0
votes
1
answer
20
views
gathering annotated classes returning generic super type of given class
In Java 17 I have a method that collects all classes above some class in the inheritance/interface hierarchy that are annotated with a certain interface. For example if MyClass implements Foo, then if ...
0
votes
0
answers
14
views
Swift Protocol Constraints Relationship
I'm trying to figure out if it's possible to create/compose a protocol relationship like this:
Considere a protocol HasAction, that needs an "enum: String" like so
protocol HasActions<...
-1
votes
1
answer
35
views
Why do I get this error when attempting to generics to implement a custom ArrayList?
I am attempting to implement an sub class that extends ArrayList. This class should print the elements of an array.
import java.util.ArrayList;
public class MyArrayList <T extends ArrayList> {
...
2
votes
2
answers
65
views
Accommodating heterogenous receivers in a Go constraint
Context
This question is about defining the canonical, proper, or best-practice approach for defining type-constraints for types with a mix between pointer and non-pointer receivers. I define a few ...
0
votes
1
answer
41
views
Interface and Generics Type Mismatch - Required Nothing
Summary:
Type Mismatch when using Generics and Star Projection
Needed Type is a Generic as well - Nested Generic?
Reproducible Code Below
Question:
My intent is to be able to use and extend an ...
0
votes
0
answers
29
views
Why does decimal.Radix result in a CS0117 Error? [duplicate]
TL;DR How do I access Decimal.Radix?
For the learning of it, I am trying to implement my own fraction type. The type should implement System.Numerics.INumber<TSelf>, which includes System....
0
votes
1
answer
45
views
Implementing a generic function for a trait, which can operate on different number types
Is there a better way to implement a common conversion function over primitive number types? I've been struggling to create a more generic version of a trait, that converts a LE byte stream to ...
1
vote
1
answer
31
views
Identity type in Typescript [duplicate]
Can the identity type be expressed in Typescript?
I know that the identity function can be type as
type IdentFunc = <T>(input: T) => T
Since all generics are on the right side of the type, ...
-1
votes
0
answers
23
views
Looking for cleaner way to handle a potential nullable conversion to generic type
Here's my code:
PropertyType GetSamplePulledDate<PropertyType>()
{
DateTime? date = String.IsNullOrEmpty(PropertyEditor.DtPckerSamplePulled.Text)
? null
: ...
0
votes
0
answers
38
views
Generic struct that can hold either Rc<RefCell<T>> or Arc<RwLock<T>>
I'm struggling with the implementing a struct in Rust that is able to hold either Rc<RefCell<T>> or Arc<RwLock<T>>.
The motivation of such a design is to allow the user to use ...
0
votes
1
answer
23
views
Is there any way to type erase only the parameter of closure in Swift?
Here's my code:
init<T: RandomAccessCollection>(
items: T,
build: @escaping (T.Element) -> any View
) where T.Element : Hashable {
self.items = ...
0
votes
1
answer
32
views
How to return an instance of a derived generic class when a base class is expected using static factory methods? [duplicate]
Using the Result pattern, I want to implement a ValidationBehavior using FluentValidation and MediatR. The behavior's return value should either be a Result or a Result<TValue>.
My base Result ...
1
vote
1
answer
32
views
How can I have an optional TypeVar in a Generic class in Python?
I'm trying to write a simple type wrapper to represent the interface of decorator functions:
from typing import Protocol, TypeVar, Generic
TIn = TypeVar('TIn', contravariant=True)
TOut = TypeVar('...
0
votes
1
answer
37
views
When using Generics, Parent Interface is requested and not inherited subclass
Summary:
Attempting to build a generic interface, as the functionality is the same across different custom data types
It is expecting the parent class rather than the inherited sub class
Question:
...
-1
votes
1
answer
69
views
Swift Generic empty Array & Dictionary initialization
I try to solve generic condition that I want to return empty array or dictionary when the Element is Optional Type.
Code:
private func findOut<T: Any>() -> T {
if T.self is String....
1
vote
1
answer
35
views
What is the difference between "x is T" and "(x as? T) != null"?
In Kotlin, when writing a generic, non-inline function, x is T throws a compiler error due to type erasure.
fun <T> example(foo: Any, bar: T) {
if (foo is T) { // compile error
// ......
1
vote
2
answers
69
views
Java generics and collections: Why it is possible to assign float list to List<? super Integer>?
In Java generics topic stated, that expression `? super Integer` means any type(class) that has Integer as super class(Including Integer.class).
Then why following behavior possible?
List<? super ...
2
votes
0
answers
37
views
How to avoid lambda implicit conversion to return type Unit when passed as a function parameter?
Given a wrapper type, eg Promise<T>, how to write a type safe resolve(block: () -> T) method where Promise<Unit>().resolve{ getInt() } doesn't compile.
While an () -> T expression is ...
2
votes
2
answers
81
views
List of generic structs / interfaces in Golang
Is there a way to have a list of generic structs/interfaces in go?
Here is the thing I'm trying to achieve.
package main
type List[T any] struct {
Elements []T
}
func (f *List[T]) Add(el T) {
...
0
votes
0
answers
44
views
Impl trait method on generic and vec of generic within a struct
I'm trying to implement the approx crate traits for a struct and it's fine with the values that are f64, but I don't know how to implement for the Vec values.
The struct is
pub struct Body<T> {
...
0
votes
0
answers
27
views
Does the Java compiler know that t.getClass() always returns Class<T>? Can it be made aware of method contracts?
Do I understand correctly that the Java compiler is unaware of the fact that t.getClass() always returns Class<T>?
public ObjectField(T object, FieldExtractor<T> fieldExtractor) {
...
1
vote
1
answer
78
views
Create a TypeScript object and define its type based on constraints from an input object
I'm trying to write a function which takes an object A: { [key: string]: string | undefined } as input, and outputs a new object B such that all properties in A are present in B, each string property ...
0
votes
0
answers
34
views
Can a variable with a generic parameter as the base class be used to reference a variable with a generic parameter as the derived class in C#? [duplicate]
DataModel Class Inheritance:
BaseLine
Line: BaseLine
PolyLine: BaseLine
Render Class Inheritance:
BaseRenderComp<T> where T : BaseLine
LineRenderComp: BaseRenderComp<Line>
...
4
votes
1
answer
31
views
What is the difference between <T> and <T : Any>
In Kotlin, what is there difference between the following two functions:
fun<T> List<T>.myFunction() { ...
fun<T : Any> List<T>.myOtherFunction() { ...
Presumably this Any ...
0
votes
1
answer
49
views
Type inference in generic structs in Go
Consider the following code
import "fmt"
type key1 int
type key2 string
type value int
type m1 map[key1]value
type m2 map[key2]value
type A[key key1 | key2, t ~map[key]value] struct {
...
0
votes
2
answers
41
views
Func as a property with types it doesn't know about
Is a way, in C#, to have a Func as a property of a class, but for it to refer to a type that it doesn't know (or care) about?
For example, let's say we're trying to define a filter:
Project A:
// ...
0
votes
0
answers
5
views
Passing both generic list and different types of elements(char, bool, int ) to a single method in java
public class IteratorExample {
public static <T> void main(String[] args) {
List<T> tList = new LinkedList<>();
addDataToList("First Element", tList);
...
0
votes
1
answer
24
views
Sorbet won't allow Zlib::GzipReader as a parameter to a method
This Ruby code with a Sorbet signature:
sig { params(source: T.any(String, Zlib::GzipReader)).returns(T::Boolean) }
def file?(source)
source.is_a?(String) && File.exist?(source.to_s)
end
...
0
votes
1
answer
34
views
Rust Specs Crate Generic Component in System
I am trying to implement a system to use a generic component, but I keep having issues with join method when I try to mutate the variable. Here is a simplified version of the code I have:
use specs::{...
0
votes
0
answers
12
views
Error [TS2344] when I type a generic for any class
I have an error that seems a bit strange to me
I have the following:
class A {
some?: string
constructor(some: string) {
this.some = some
}
}
type LikeClass<TClass extends { ...
0
votes
1
answer
68
views
How can I use generic structure with JsonSerializable
Since my data can be of Cart or List type, I wanted to use a generic structure.What could I have done wrong in my code when using generic type with JsonSerializable?.My codes are as in the photo. How ...
0
votes
0
answers
12
views
Is second-order generic type inference suported in modern Python (3.11+)?
First things first, I'm very much a n00b in Python programming. My background is in Haskell, Ocaml, modern C++, F#, C#: all of these are strictly typed languages with different approach to generic ...
0
votes
1
answer
35
views
How to type-hint a variable whose type is any subclass of a generic base class?
I have two abstract base classes that are linked, and should be subclassed together. For the sake of a minimal example, let's say its some class TobeProcessed, and a another class Processor that ...
0
votes
0
answers
27
views
unknown type name macro coding preprocessor [closed]
`When I run a test file on my hashltable.h, one of the errors says :
In file included from src/hashltable_test.c:2: src/hashltable.h:250:50: error: unknown type name ‘typkey’ 250 | int ...
-1
votes
1
answer
41
views
How resolve all actual types of an implementation class relative to a generic class or interface in java?
I'm trying to resolve all actual types of an implementation class relative to a generic class or interface.
I have written an ActualTypeArgumentsResolver for this, but it only works when the TypeName ...
0
votes
1
answer
39
views
How do you define a static method collection in a generic struct
I am trying to use a collection of static method as generics inside a struct in order to change the behavior of a part of my code simply by changing the implementation of my trait.
My issue is that I ...
0
votes
1
answer
33
views
Specify only a subset of Type Arguments when calling a Generic Method? (Java)
Suppose I have the following method declaration:
public static <E, RetType> RetType doSomething(
E instance,
String methodName,
Object... params
) {...}
...
4
votes
1
answer
82
views
Go: How to specify a type constraint in which a method's argument type is the same as that of the receiver
I would like to specify a type constraint like the following:
type Comparer interface {
Compare(another Comparer) int
}
But I want the implementing type to pass in the concrete type of itself ...
2
votes
1
answer
67
views
Implementing interface methods with generic type structs in Go
I want to have an interface which can take any type of parameter to its single method, and I want to have a single implementation struct with generics.
Here is a super simplified version of my problem:...
0
votes
2
answers
30
views
Typescript Generics: How to restrict key of record to be string?
Typescript here complains:
Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'.
type TableProps<Row extends Record<string, ...
0
votes
0
answers
28
views
Can I use recursive macros in trait bounds like this?
I'm trying to implement a macro that seems to be slightly beyond my macro-fu.
The macro generates an impl<...> Trait (...) for generic tuples of different sizes, but I need the each type of the ...
0
votes
1
answer
40
views
Matching nested generic type
For the sake of learning I'm writing my own functor implementation. Function-wise it makes no sense, but it acts as a nice way to learn how the language works and how to implement more complex ...
0
votes
1
answer
38
views
Kotlin sorting generic collections
I have some inline function for filtering query data, like this:
inline fun <reified T> findByFilterFunc(filter: String, em: EntityManager, offset: Int, limit: Int, sortName: String?, ...
2
votes
1
answer
51
views
Static typing of the parameters of a Generic type
If I have "factory" method, taking a class type and the relevant parameters to create a resource, is there a way to have static analysis of the parameters?
from typing import Type
from ...
1
vote
2
answers
54
views
Create EnumMap from generic enum
I have a class parametrized with generic enum, like this:
public class SomeClass<E extends Enum<E>> {
public void someMethod( ) {
// I want to initiate a map like this:
Map<E, ...
-4
votes
1
answer
79
views
Why can I create Comparable objects with operator "new"? [closed]
Why is
new Comparable[]
correct code in Java? I have seen code like this
public class ArrayHeap<T extends Comparable<T>> implements Heap<T> {
...
public ArrayHeap(int ...
-1
votes
1
answer
65
views
Java : generics, inheritance and best design
I have a basic processing interface :
public interface Processing<T> {
void appendTo(T t);
}
And this inheritance tree :
public class Animal {
}
public class Dog extends Animal {
...
0
votes
3
answers
53
views
Type A is assignable to the constraint of type T, but T could be instantiated with a different subtype of constraint A | B
I get this error from TS and it doesn't make any sense,
because my T generic is fully compatible with types A | B, because it extends from it! It's is not true what the error says that you can ...
0
votes
0
answers
38
views
Hard problem with generics in Java Generics extremly hard problem, nearly unsolvable, 3 problems
Hey I have a problem with generics in Java.
I need to create an XList class, providing additional capabilities for creating lists and operating on them.
The class should contain appropriate ...