51,705 questions
0
votes
1
answer
38
views
Subclass of Generic fails with AttributeError: object has no attribute '__parameters__' - using Generic when superclass does forward __init_subclass__
I have a setup like the following
from typing import Generic, TypeVar
T = TypeVar("T")
class ThirdParty:
def __init_subclass__(cls):
... # does not call super()
class Mine(...
-1
votes
2
answers
103
views
ArgumentException when calling MethodInfo.MakeGenericMethod
public void Test<T>(T reference, T same, T differentOrGreater)
{
var comparisonInterface = typeof(T)
.GetInterfaces()
.FirstOrDefault(
i => i.IsGenericType &...
0
votes
0
answers
33
views
Call GORM's .list() in trait with generic type
In my Grails 6 project, I'd like to add an additional feature to select domain classes, so I defined a custom trait.
trait MyDomainClassTrait<D> implements GormEntity<D> {}
// domain ...
0
votes
0
answers
39
views
How to use the new generics feature in TwinCAT 3 structured text
I have the following function block:
FUNCTION_BLOCK FB_GenericsTest
VAR_GENERIC CONSTANT
SIZE: INT := 1;
END_VAR
Which has this FB_Init method:
METHOD FB_Init: BOOL
VAR_INPUT
bInitRetains: ...
1
vote
1
answer
73
views
Rust generic type results in trait not found anymore
Rust newbie here.
The following code throws a compiler error:
#![feature(portable_simd)]
use std::simd::Simd;
use std::simd::SimdElement;
fn test_mul<T: SimdElement, const N: usize>(x: [T; N]) ...
Best practices
0
votes
1
replies
55
views
How to constrain an interface to be only applicable for slices or maps
I've got a Matcher interface in Go that is implemented by quite a lot of underlying types.
I'd like to restrict the Matcher interface such that implementing types can only be a "collection", ...
-1
votes
0
answers
43
views
Order of associated generic types in Rust, which one is better? [closed]
trait Sub {}
trait Super {
type SubT: Sub;
}
// Should we write
struct SuperFirst<SUP, SUB> {
// Fields are private
sup: SUP,
sub: SUB,
}
fn build_1<SUP, SUB>(_: SUP) -&...
-2
votes
0
answers
57
views
Why can PropertyColumns not infer their type parameters when passed to a wrapper? [duplicate]
I am using MudBlazor's MudDataGrid, which functions very similarly to Blazor's QuickGrid. The grid's contents are determined by a RenderFragment parameter called Columns, which contains a list of ...
3
votes
1
answer
177
views
if statement with is operator and Generics fails even when debugger shows correct type
I am implementing a message passing mechanism in a multi-threaded Delphi 2010 VCL application. My background threads need to send various DTO records to the main UI thread. I am using a generic ...
2
votes
1
answer
119
views
_Generic in C is making me go insane [duplicate]
Take a look at my code:
#include <stdio.h>
#include <stdlib.h>
#define add_int(a, b) ((a) + (b))
typedef struct matrix
{
int** data;
int n_rows;
int n_columns;
} matrix;
...
3
votes
3
answers
147
views
Symbol not found error with complex generics and lambda arrangement
The following test renders fine in my IDE (Eclipse), but fails to compile when building via Maven.
The compiler error is shown in the comment line in the code block below.
It looks like the compiler ...
3
votes
1
answer
179
views
How to handle Delphi generic constraint as 'inherits from' class
When trying the following code it will not compile as I receive this error:
Type parameter 'T' is not compatible with type TBase
I want this type constraint to support the Save method being typed to ...
2
votes
1
answer
152
views
How do I use .NET reflection to emit generic interfaces and a class which implements them
I am trying to use .NET reflection to emit a class and some interfaces which the class implements. However, I cannot seem to correctly implement the interfaces that are generic, as that results in ...
1
vote
1
answer
113
views
Avoid boxing of generic enum type
Given the base class:
public abstract class EnumType<TEnum, TValue>
where TEnum : struct, IConvertible
where TValue : struct
{
public abstract TEnum GetEnumValue(TValue value);
}
...
Best practices
0
votes
2
replies
44
views
How to create a type safe functional extension in Kotlin with generics
I am expecting that only the first line of main function will be compiled.
fun<T> T.shouldBe(arg:T) : Boolean {
return this == arg
}
fun main() {
1.shouldBe(2)
1.shouldBe(true)
...
1
vote
1
answer
91
views
Generic method cannot invoke specialized implementation?
It is possible to make a call to a specific implementation of a generic method on a struct, ex:
impl Printer<i16> {
pub fn run() { println!("Specific i16"); }
}
Printer::<i16&...
1
vote
1
answer
93
views
Python 3.12+ generic syntax for <T extends Foo>
Python 3.12 introduced new syntax sugar for generics. What's the new way of writing an upper-bounded generic like this:
def foo[T extends Bar](baz: T) -> T:
...
Before new syntax features I ...
2
votes
2
answers
239
views
In Delphi, is it possible to create a new generic class from the unconstrained generic base class and a provided type?
I want to be able to write a function such as below, but can't get the typeinfo or type reference for the unconstrained generic type of TMyBase<T>.
type
TBase<T> = class
end;
...
0
votes
0
answers
118
views
ClassCastException when comparing elements in custom ArrayOrderedList using Comparator
I am implementing an ordered list that automatically inserts elements in the correct sorted position using a Comparator. The list is built from scratch (not using java.util.ArrayList) and uses an ...
Advice
0
votes
8
replies
114
views
C# using generic types to represent a partially loaded tree of data
The problem I am trying to solve is representing a partially loaded tree of objects using C# generics. For example, suppose we have the following classes:
public class Address
{
public string ...
4
votes
1
answer
142
views
Type inference breaks when using two type mappings in one type
I have the code below.
import React from 'react';
type Button = React.ComponentType<{ size: 's' }>;
type Select = React.ComponentType<{ color: string }>;
declare const button: Button;
...
5
votes
1
answer
132
views
Rust specifying a trait and associated type are valid for the lifetime inside a function
I am using the winnow crate to write a parser and am struggling with
adding tests due to lifetime conflicts.
The basic setup I have is a stateful stream:
// The primary stream type
type SStream<'i, ...
0
votes
2
answers
109
views
Is it possible to use generic argument of a type for its attribute parameter (JsonConverter)?
Use case: I want to write a JsonConverter for a generic type like this, but I cannot apply it to the type itself:
public class EditingModelConverter<T> : JsonConverter<EditingModel<T>&...
2
votes
2
answers
126
views
C# Pass null to Generic Method Receiving Nullable Type [duplicate]
The following code generates CS1503 with the message:
error CS1503: Argument 1: cannot convert from '<null>' to 'T?'
public class MyClass<T> where T : notnull
{
// This is the only ...
-3
votes
3
answers
255
views
How can I generically convert a String value into an instance of a given Comparable type in Java?
I’m trying to implement a generic utility method that takes a String value and a Class<?> type, and returns an instance of that type.
The context: This value represents data from a JPA column, ...
4
votes
0
answers
106
views
Narrowing dict to TypedDict
I want to narrow an unambiguously defined dict[...] type in a superclass to a specific TypedDict in an inheriting class but I cannot figure out a way to specify a dict-based supertype that the ...
2
votes
6
answers
145
views
How do I find out the type of items in a generic type collection?
I want to write a method that converts a collection of generic type elements into a human-readable string. This method should also work with nested collections. I haven't found a better approach than ...
0
votes
0
answers
94
views
How to call a generic C# function from Powershell? [duplicate]
In YamlDotNet source, there is function with a definition of:
public static bool Accept<T>(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent
and which is called ...
0
votes
0
answers
96
views
Declaring an array of weak referenced protocols gives error: 'Weak' requires that 'any LocationSendingDelegate' be a class type
I need to store an array of weak referenced protocols:
class Weak<T: AnyObject> {
weak var value: T?
init (_ value: T) {
self.value = value
}
}
protocol ...
0
votes
1
answer
87
views
Deducing instance to handle an object in C#
I am extending my C# J2K library to dynamically register codecs from other assemblies. That part is working, but I am having trouble understanding IsAssignableFrom(TypeInfo) and how I can deduce which ...
0
votes
0
answers
49
views
Is Swift generic SIMD code much slower than direct SIMD
I have written a SIMD interpolator like this:
public struct Fade_SIMD8 {
public init() {}
public func interpolate(_ t: SIMD8<Float>, between a: SIMD8<Float>, and b: SIMD8<...
-3
votes
1
answer
194
views
How to convert T to INumber [closed]
How would I convert T to INumber? Please see my example below.
The problem here is that I need a generic function that does different things depending on whether the type is INumber or not.
void Func&...
1
vote
1
answer
60
views
How to define a generic type with `new(...args)` in TypeScript?
In TypeScript, it is possible to define a type of a constructable class using new(...args: any):
// We have some class inheritance
abstract class Something {}
class ChildOfSomething extends Something {...
0
votes
1
answer
55
views
Django Generics custom quering
I was working on notion like app, so I have a Note(consider as a Page in notion) and in that i am having blocks, where block having different id's and held with Note in Foreign field so now in views ...
1
vote
0
answers
44
views
Issue with generics in Java extending another class and Spring ParameterizedTypeReference
Using RestTemplate in Spring Boot to connect to a server, I have this generic class to map responses from the server I'm connecting to:
@Data
public class ServicesResponseDTO<T> implements ...
3
votes
2
answers
106
views
Any way to check a cast to a generic?
I am working on a Spring Boot application and there I use JWE - tokens. When generating these tokens I serialize a given DTO. As an example, the generation of an AccessToken looks like this:
public ...
1
vote
0
answers
89
views
How to access DbSet properties at runtime [duplicate]
I am very new to development with ORMs.
In my project, where I use Entity Framework Core, I want to create a class that would encapsulate whole interaction with database, i.e. through which I would ...
9
votes
2
answers
189
views
Why is Java unable to infer the type when comparing Map.Entry objects?
Why does the following cause a compilation error?
One
Map<Integer, Integer> map = new HashMap<>();
List<Integer> numList = map.entrySet().stream()
.sorted(Comparator....
2
votes
3
answers
78
views
Is there any way to shorthand multiple parameterised types
Say I have the following trait and classes:
trait T[C1, C2, C3, C4]
case class A() extends T[Int, Double, Long, String]
case class B() extends T[Int, Double, Long, String]
case class C() extends T[...
3
votes
2
answers
135
views
How to deal with incompatibility of similar instances of generic packages defined in different translation units in Ada?
I've created a generic package called Generic_Functions which must be instantiated in similar fashion to the standard Ada.Numerics.Generic_Real_Arrays and has next specification:
with Ada.Numerics....
2
votes
3
answers
190
views
Why does Java give a warning for casting Collection<? extends Number> to List<Number> but an error for assignment?
I’m trying to understand the difference between assignment and casting in Java generics. Consider the following examples:
List<Integer> ints = new ArrayList<>();
List<Number> nums = ...
3
votes
1
answer
92
views
How to check if a type is an boxed/existential/protocol type?
I already know it's possible to check if a type is a class.
func isClass<T>(_ value: T.Type) -> Bool { T.self is AnyClass }
func isClass<T>(_ value: T) -> Bool { T.self is AnyClass }
...
0
votes
1
answer
82
views
Can muli-inheritance be simulated with generic class in C# [closed]
I have several DataGrid (actually an UserControl based on a DataGrid with filtering dialog, etc.) in a WPF project which show ObservableCollection<VisualXModel> entities where VisualXModel ...
18
votes
1
answer
1k
views
List<T>.ForEach does not invoke the action HashCode.Add<T>
In C#, using the structure HashCode and the List<T>.ForEach method shows a behaviour that I cannot explain:
The two snippets below do not return the same result:
Working as expected:
var ...
3
votes
2
answers
147
views
Map a generic type to an instance of its type
I have the following inheritance structure:
class S:
...
class A(S):
...
class B(S):
...
I'd like to conceptually do something like the following:
class Foo:
T = TypeVar('T', bound=...
1
vote
0
answers
75
views
Return Subclass type from Parent function [duplicate]
Question
In the example below, childOfNumbers is correctly inferred to be Child<number>. However, my issue is childOfStrings is inferred to be Base<string>. Is it possible to have a parent ...
2
votes
1
answer
140
views
Haskell parameter function that itself has a type parameter
I'm trying to write a function that performs a binary operation on either floating-point numbers or integers. My attempt:
data MyNum = F Float | I Int
performBinaryOperation :: (Num a) => (a -> ...
3
votes
1
answer
137
views
How to cancel a “range over func” iteration early with context.Context in Go 1.22+ without leaking goroutines?
Go 1.22 introduced iterating over functions with for ... range. I’m trying to make a generator that respects context.Context so that breaking early doesn’t leak a goroutine.
package main
import (
...
1
vote
1
answer
76
views
Predicates with generics
I’m trying to use Predicate with generics but I keep getting the following compilation error :
Cannot convert value of type 'PredicateExpressions.Equal<PredicateExpressions.ConditionalCast<...
1
vote
1
answer
203
views
How to Check the Actual Type of a Generic Parameter in a Python Generic Function to Narrow All Parameters of Type T [closed]
I am working with a generic function in Python and trying to understand how to properly check the actual type of a generic parameter to narrow the type of all parameters bound to the same generic type ...