51,719 questions
Advice
5
votes
3
replies
99
views
Type narrowing a generic sequence argument in python
Afternoon,
Is it possible in python, given a function that takes a generic sequence of objects, to type it so that the list must be of only one type and not a union of multiple children?
for code like ...
Best practices
0
votes
3
replies
46
views
Ways to hint the compiler about return type when calling generic function
A nice generic function I use to call python functions in another process, using Json....
inline fun<reified Tin0, reified Tin1, reified Tout> callPy2(
methodName:String, input0: Tin0, ...
4
votes
1
answer
126
views
Template method return type not matching returned instances
I am having a problem with a static template method in an interface. There is nothing special about the interface but the method declaration is a bit tricky. The code looks like:
public interface ...
Advice
1
vote
4
replies
88
views
Generic Type Info at Runtime (Java)
I was reading about Generics from the Eleventh Edition of "Java The Complete Reference", specifically the "Run-Time type Comparisons with a Generic Hierarchy" part.
I was confused ...
Advice
0
votes
8
replies
135
views
How can I allow the user to use class specific methods in generic class T?
I am making a custom LinkedList<T> in Java, as a way to learn more about data structures, and I am trying to make a search method that filters items based on the input, but I ran into an issue. ...
0
votes
1
answer
115
views
While implementing custom stack I got type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Stack<T>' [closed]
I am getting this error while implementing a stack by myself.
Here is my code
interface IStack<T> where T : class
{
void Push(T item);
T Pop();
T Peek();
bool IsEmpty { get; }
...
1
vote
2
answers
154
views
.NET ReadFromJsonAsync<List<T>>() throws JsonException when API response contains wrapper object
I am developing a layered .NET project with API, BLL, DAL, and UI layers.
The UI layer calls the API using a generic API repository built with HttpClient.
My project structure is roughly like this:
...
1
vote
1
answer
82
views
Using trait bound as type in generics
I'm having trouble with implementing a trait bound generic parameter for an entity that sends messages to a proper entity depending on the message. Imagine a trait called MessageTrait and ...
5
votes
1
answer
88
views
Why does TypeScript distribute conditional types over union types only when the checked type is a naked type parameter?
I’m trying to understand how conditional types behave differently when a type parameter is “naked.” For example:
type Wrapped<T> = [T] extends [string] ? "is string" : "not string&...
1
vote
3
answers
114
views
How to call a method with generic parameter of a self referencing generic interface?
If given a generic interface of which generic is a reference to this generic interface itself, and this interface has a method with parameter as generic type. After implementing this interface with a ...
2
votes
1
answer
158
views
Multiple upper bounds for a generic type parameter
I have an interface and a class in kotlin. For example, interface A and class B.
I want to write a function or a class with generics that will accept as generic all types that are subclasses of both A ...
0
votes
0
answers
46
views
Uncontained snap Carousel with ScrollView
I'm trying to make a generic snap carousel using ScrollView but stuck on over-scroll behavior of the ScrollView. When over-scrolled the re-calculation creates a jittered animation ripple. I want the ...
3
votes
1
answer
65
views
Kotlin removeAll function with MutableCollection receiver - both in/out modifiers are used
In Kotlin, the removeAll extension function on MutableCollection with Iterable argument is defined as (see reference here):
@IgnorableReturnValue
fun <T> MutableCollection<in T>.removeAll(
...
3
votes
2
answers
169
views
How to convert to string an 'allows ref struct' generic argument?
I have a method that accepts a T generic argument. The T has the allows ref struct anti-constraint. Now I want to validate this argument, and in case of failure to include the value of the argument in ...
1
vote
2
answers
176
views
How to make a type depend on a constant generic parameter in Rust?
I am very new to Rust. I want to have a type depend on a constant generic parameter in Rust. In C++, this can easily be achieved with some metaprogramming:
template<std::size_t N>
struct ...
2
votes
1
answer
170
views
iteration over integer range doesn't work with generic type constrainted to integer
Go v1.22 added the ability to easily range from 0 to n-1:
// Prints 0, 1, 2 on separate lines.
for i := range 3 {
fmt.Println(i)
}
However, it doesn't work as expected when the expression's type ...
3
votes
1
answer
99
views
Kotlin plusAssign function on MutableCollection - Array type parameter T not marked as out
In Kotlin, the plusAssign (+=) operator function on MutableCollection with Array argument is defined as (see reference here):
inline operator fun <T>
MutableCollection<in T>.plusAssign( ...
0
votes
1
answer
125
views
How to apply a two-levels' SelectMany using expressions in a generic way in C#
Let's have 3 entities with the same base class for ID's:
public class EntityBase
{
public int Id { get; set; }
}
public class Company : EntityBase
{
public string Brand { get; set; }
public ...
1
vote
2
answers
67
views
Making a Type Alias Resolve to Different Types Based on Constant Evaluation in Rust
I would like to define a type alias so that it resolves to different types based on an evaluation, something like so:
struct Example0;
struct Example1;
type Maybe<const B: bool, T, F>;
//Define ...
0
votes
1
answer
116
views
How to restrict generic type parameters to a set of classes? [duplicate]
I want to restrict generic type params to a certain set of interfaces and their implementors and/or classes and their inherited child classes.
I my concrete case, I want that typeparams TIn and TRet ...
2
votes
1
answer
109
views
Generic interface with default implementations
I have this interface:
public interface IDebugEndPoint
{
void InstructionReady(ICPU cpu);
}
where ICPU is implemented by many concrete CPU types. I pass an IDebugEndPoint to an ICPU for "...
-1
votes
1
answer
112
views
"assignable to" type constraint for generic type parameters
Consider the following (playground):
import "fmt"
type Gizmo string
func (g Gizmo) String() string { return string(g) }
func Convert(in []Gizmo) []fmt.Stringer {
out := make([]fmt....
4
votes
0
answers
132
views
How to make a generic specifiable associated type in Swift?
I'm trying to make a backport for integer generic parameters and a fixed size array that is stored on the stack (backporting InlineArray in short terms):
// Simplified, normally there is a way to get ...
1
vote
1
answer
112
views
Android Custom UI Component with Generic Type
I have created a custom spinner in Java for Android and my class uses generics as such
public class TLPSpinner<T> {
I have an event that fires when a object is selected and if instantiate the ...
1
vote
0
answers
87
views
Why does this generic function work for arrays but fail for strings, even though both have slice()?
I am trying to understand TypeScript generic constraints and type inference.
I have the following function:
function cutValue<T extends { slice(start: number, end?: number): T }>(
value: T
): ...
2
votes
1
answer
60
views
How do you write generic function as an argument for a function when the generic function signature isn't related to calling function signature?
typescript sandbox
I want to have a function which calls provided function, returns its value, in case this value is null return undefined. Also it has to swallow any error and return undefined.
So a ...
5
votes
0
answers
135
views
Can someone help explain Python's mypy issue with Incompatible return value type due to covariance when returning a sub type of a union
Apologies if there is a straightforward answer already that I'm too smooth brained to see. I am working with Python 3.13+ and Mypy 1.19.1. I've read mypy's docs, read several similar questions/answers ...
1
vote
0
answers
97
views
Java interface return specific raw type with different generic type parameter [duplicate]
Is it possible to Java to model a (generic) interface that defines a method that is required to return a generic type that is required to be of a certain raw class? I want to model a container-like ...
4
votes
2
answers
218
views
Java 21 and Generic types wildcard capture issue
I am working on a small side project that uses a very simple command handler pattern for dispatching command classes to handler classes. I come from a C# background, and am running into an issue with ...
3
votes
1
answer
83
views
Conflict on generic TryFrom impl but not on generic From impl
I'm trying to implement TryFrom over a type parameter, like so:
enum MyType {}
struct MyError();
impl<T: Into<u8>> TryFrom<T> for MyType {
type Error = MyError;
fn try_from(...
0
votes
1
answer
117
views
incompatible types: inference variable V has incompatible bounds (SSE / Jackson)
With the deprecation of MappingJacksonValue in spring boot 4/Jackson 3, I'm trying to figure out how to serialize my objects based on a JsonView.
I have the following SSE endpoint :
@GetMapping(...
4
votes
1
answer
127
views
How to type hint class tuple itself not instance without pylance complaining
I'm trying to hint that a Pydantic BaseModel field needs to be the class tuple or one of its subclasses, so I've typed the field as type[tuple]:
from pydantic import BaseModel
class Task1(BaseModel):
...
Advice
0
votes
0
replies
71
views
Generic constraints definitions that are derived/related in TypeScript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
I'm only a week into learning TS, and I was only wondering why this couldn't be written as
function getProp&...
1
vote
0
answers
126
views
How to find fragment interface generic type
I am trying to create a custom generic repository using the fragment interface approach as described in this article: https://docs.spring.io/spring-data/jpa/reference/repositories/custom-...
2
votes
1
answer
91
views
Instantiation of type with recursive type constraints
The Announcing F #7 page gives the example code
type IAddition<'T when 'T :> IAddition<'T>> =
static abstract op_Addition: 'T * 'T -> 'T
type Number<'T when IAddition<'T&...
Advice
3
votes
8
replies
114
views
Implement an interface method with a type parameter
Suppose there's an interface
interface IAnimal {
IFood GetPreferredFood();
}
and a class
class Cat<F>(F food) : IAnimal where F : IFood {
private F _food = food;
public F ...
Best practices
0
votes
1
replies
44
views
How to type a generic SimulationEvent and engine in Python without “TypeVar bound type cannot be generic” errors?
I'm building a simulation engine in Python and want to use generics so that events are strongly typed to a simulation state. I have something like this:
from __future__ import annotations
from abc ...
2
votes
1
answer
76
views
Shortcut/Simplification of generic pattern 'X extends Y = Y'?
I find myself having to write X extends Y = Y a lot when creating types in TypeScript, for example:
type T<V extends X = X> = ...
When my types get very long (working on a personalized, type-...
3
votes
1
answer
105
views
Is it possible to dispatch on a "name" object?
I have an object that could be either a "name" or a "call", and I want it to end up as a "call". By a "name" object, I mean like something created by bquote(), ...
Advice
0
votes
1
replies
61
views
Why can a parameter-less anonymous method be assigned to a delegate Action<T> that expects a parameter?
I'm learning about delegates in C# and came across a pattern that I don't fully understand. I have a generic method that returns an Action<T>, which I expect to be a method that accepts one ...
Advice
0
votes
4
replies
72
views
Lower Bounded Wildcards: is it about superType or subType
Oracle documentation mentioned it clearly.
a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.
To write the method that works on lists of Integer ...
0
votes
1
answer
113
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
109
views
ArgumentException when calling MethodInfo.MakeGenericMethod [closed]
public void Test<T>(T reference, T same, T differentOrGreater)
{
var comparisonInterface = typeof(T)
.GetInterfaces()
.FirstOrDefault(
i => i.IsGenericType &...
0
votes
0
answers
54
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 ...
1
vote
1
answer
148
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
96
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
68
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", ...
3
votes
1
answer
192
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
135
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
157
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 ...