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).
47,612
questions
0
votes
0
answers
9
views
TypeScript: Generic function which returns the same type as parameter
Consider this (which doesn't compile):
function roundTo<T = number | null | undefined>(
num: T,
decimals: number,
): T {
if (num === null || num === undefined) return num;
const factor =...
0
votes
2
answers
21
views
java generic two left hand side parameters how to interpret
I was researching creating a generic sprint webflux based HTTP client and ran across code
public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
is that the same as <...
0
votes
1
answer
11
views
Currying with bind function and to correctly type with generic in TypeScript
I have written a sort function and would like to bind a compare function to it. Unfortunately, the TypeScript compiler warns me for unknown type for the compare function.
I have tried search for SO: ...
0
votes
0
answers
25
views
How to pass an entire typecsript Enum as a component input on Angular?
I have a generic component that receives a Enum as input:
TableComponent<Columns> {
@Input() columnsEnum: Columns;
}
The Enum looks like this:
export enum CardsEnum {
CODE = 'sCode',
...
0
votes
2
answers
14
views
C#7: How to use tuples in generic methods (LINQ select example)
I have some heavily repeating code, which has always the same structure, just using different columns in a database for accessing it and doing similar stuff
A typical query looks like:
var ...
0
votes
3
answers
44
views
Java implement class in interface
Say I have the following classes:
public abstract class Crop {
}
public abstract class Fruit extends Crop {
}
public interface Edible /* ALWAYS IMPLEMENTED BY A CROP */ {
}
public class Apple ...
2
votes
1
answer
61
views
Is it possible to contraint a generic parameter type to this?
Short version
How do I force the BaseClass's TModel generic parameter to be of the same type as the class that derives from it?
public class BaseClass<TModel, TValidator> where TValidator : ...
0
votes
1
answer
55
views
C# generic bounds
I have a abstract dto class,I want to write a batch class to deal the derived dto:
dto:
public abstract class Command
{
private string TraceNo { get; set; }
public override string ...
0
votes
0
answers
18
views
Blazor generic component - unknown prop
this is my search metod in generic component:
private ICollection<TItem> GetItems(string text)
{
return DataToSearch.Where(x => x.ToString().ToUpper().Contains(text.ToUpper())).ToList();
...
0
votes
0
answers
11
views
Go: difference between any and interface in varargs [duplicate]
In Golang 1.18 I can do this:
func foo1[T any](items ...T) {
// do something
}
func foo2(items ...interface{}) {
// do something
}
Both of these appear to accept a list of objects whose type ...
0
votes
2
answers
33
views
How to use generics for type safety while using `removeRange` method of ArrayList
Since the method - removeRange(int startIndex, int ) is protected, we need to use it in a class extending ArrayList. Below is my code -
public class MyClass extends ArrayList<String> {
...
0
votes
0
answers
31
views
Java Generics - Class cast exception
public class Test {
public static class Data{
List<? extends AbsModel> definitions;
public Data(List <? extends AbsModel> definitions) {
...
0
votes
1
answer
33
views
Best Way to Retrieve Actual Concrete Object Of a Certain Type From a Json-String in C#?
I'm currently struggling with determining which types a json-string deserializer gives back in C#. I've tried to make a base TypeWHATEVER class where TypeX and TypeY inherited from them, but still ...
0
votes
1
answer
42
views
Using non-monomorphizable generic parameters in a function
I want to write some code that should be generic across implementors of a particular trait, but whose exact type can't be known until runtime.
In particular, I want to apply a function from PartialOrd ...
3
votes
1
answer
37
views
typescript difference between placement of generics arguments
What is the difference between generic function syntax:
type Identity<T> = (t: T) => T
and
type Identity = <T>(t: T) => T
?
2
votes
1
answer
58
views
F#: Span, raise, and the bottom type (or lack thereof)
After I posted this comment https://github.com/fsharp/fslang-suggestions/issues/349#issuecomment-1124206512
I'm still feeling I'm missing out...
Sample code reproduced here for the reader's ...
2
votes
1
answer
16
views
It is good practice to get all object in RetrieveUpdateDestroy Method?
Why we need to get all object in RetrieveUpdateDestroy Method?
In real project can I do it just like this Without fear even if there is large data?
0
votes
1
answer
39
views
F# function with two generic parameters
How to define f# function with explicit generic parameters?
I tried this one:
let my_function<'a 'b> (xs: 'a list) (ys: 'b list) = ....
but it does not work.
0
votes
0
answers
24
views
Why don't wrapper types have generic constraints in the standard library? [duplicate]
As an example, look at the implementation of Filter, which is the return value of Iterator::filter():
pub struct Filter<I, P> {
pub(crate) iter: I,
predicate: P,
}
Notice that there is ...
0
votes
0
answers
23
views
Stream type inference not working in class with generics [duplicate]
Why does this code not compile?
package sk.qpp.tmp.generics.simple;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.Optional;
@...
0
votes
1
answer
44
views
Refactoring classes into multi-layered generic classes in C#
I have a problem with C# generics, and I'm not sure about the most elegant solution. I've been programming a while but am new to the C# ecosystem so don't know common terminology for searching.
I'm ...
3
votes
2
answers
48
views
Unioning an interface and type in golang
I'm trying to implement some caching functions in Golang but I want them to be valid for both strings and other objects that implement the Stringer interface. I'm making an attempt of it using Golang ...
0
votes
0
answers
20
views
How to backreference using inline typescript type variables
I have implemented the built in generic Omit which relies on the generic Exclude.
type MyExclude<C, E extends C> = C extends E ? never : C
type MyOmit<T, K extends keyof T> = {
[p in ...
1
vote
1
answer
29
views
Python, MyPy: how can I do an "exclusive OR" of types in a generic's restrictions?
I want to use generics so that I can avoid the "invariant Xyz" problem, and have a single source of truth for a couple of large type structure implementations, without having to Union the ...
0
votes
0
answers
15
views
Contravariance issue with generics [duplicate]
I've the below code.
interface ITest<in T> where T: Message
{
void Print(T t);
}
abstract class Message
{
}
class SimpleMessage: Message
{
}
class Test: ITest<SimpleMessage>
{
...
0
votes
0
answers
29
views
Give a name to a generic Scala case class parametrized by a specific type
I have this case class
case class MyNormalClass[T](
data: Option[T] = None,
someOtherStuff: Option[Boolean] = None
)
and I want to define a type MyParametrizedClass that is just when ...
0
votes
1
answer
33
views
Generics with moshi and retrofit
Im fairly new to Java/Kotlin, so understanding the "technical" Docs is kinda had for me.
I have an API which gives me something like this
/city/someCityName
{
"path": "...
0
votes
0
answers
21
views
pass value to generic to get type typescript
I have a function
function getExtendedObject<T extends object>( currentObject: T ) {
return {
...currentObject,
newProp: "value1",
anotherProp: () => "something&...
1
vote
2
answers
30
views
Generic where clauses with views
I have a project that allows the user to input or edit a variety of class properties. Most, if not all, of these properties will have the same input field depending on the property type; e.g. String ...
0
votes
0
answers
39
views
How to reduce generic parameters for a function in C# [closed]
I am writing a generic function which will do a full outer join between two IQueryable lists. I am getting the expected result, but the problem is with the SonarQube code quality. There is major code ...
-3
votes
0
answers
16
views
Carrer (Programmer - Engineer) [closed]
Good morning.
Im here to ask for you opinion.
I'm a former civil engineer, i've worked in a ton o companies, it's hard to say that but im really down.
i've started a new college (distance learning), i ...
5
votes
3
answers
88
views
Invariant Generics don't seem working correctly
I've read some articles about Covariance, Contravariance, and Invariance in Java, but I'm confused about them.
I'm using Java 11, and I have a class hierarchy A => B => C (means that C is a ...
0
votes
0
answers
59
views
How can a generic type be "declared" in C# [duplicate]
In the following code snippet:
public static Dictionary<int, string> myDictionary = new Dictionary<int, string>()
the type <int, string> is written twice.
Can it be this be defined ...
0
votes
2
answers
23
views
Listview for Multiple model class
how to create a listview adapter on Android Studio(Java) for multiple model class which extending parent class.
so :
gbpClass extends Money => ArrayList
eurClass extends Money => ArrayList
I ...
-2
votes
0
answers
44
views
How to make a Generic Class in Java [duplicate]
I am trying to make my own type of list class using generics. This list can be a list of double or string. So I can call on it:
myList<Double> l1=new myList<Double>();
I am new to using ...
-1
votes
0
answers
27
views
java type generic: finding an example to show Function<? super E, ? extends F> is a better choice than Function<E, F>? [duplicate]
There is class called Foo as following:
public class Foo<E> {
private E val;
public Foo(E val) {
this.val = val;
}
public <F> Foo<F> map(Function<? ...
-1
votes
0
answers
25
views
Problem with N-Input AND Gate Testbench in VHDL
I have the following file for an N-Input AND gate:
entity AND_N is
Generic (n: natural := 2);
Port (a: in bit_vector (1 to n);
b: out bit);
end AND_N;
architecture Behavioral of AND_N is
begin
...
1
vote
1
answer
32
views
java type generic: why Function<? super E, ? extends F> is more preferred than Function<E, F>? [duplicate]
There is class called Foo as following:
public class Foo<E> {
private List<E> ls;
public Foo(List<E> ls) {
this.ls = ls;
}
public void add(E l) {
...
1
vote
2
answers
107
views
+50
Barycentric rational interpolation
I'm trying to write a function which returns a function for calculating Barycentric rational interpolation in C++.
Note:
It is not at all a wise idea to recalculate weight coefficients
W, 𝑖 = 1, 2,…, ...
0
votes
0
answers
18
views
Is there a useful "number-like" generic constraint in Kotlin?
I'm writing a matrix and a vector class, and I'd like to make it usable with all "sensible" numerical data types, not only for the BigFraction data type I wrote myself for my current purpose....
5
votes
1
answer
55
views
Cannot use '<>' due to non-private method which doesn't override or implement a method from a supertype
I have the below specified behavior.
interface ValueEditorPopupView<T> {
void setValue(T value);
void setApplyEnabled();
}
abstract class ValueEditorPopup<T> implements ...
0
votes
2
answers
53
views
Use Class parameter for generic type (e.g ArrayList)
I am trying to create a generic method to handle different types of ArrayLists in Java. The types are quite different, but all contain one identical parameter, which I want to evaluate in this method.
...
0
votes
2
answers
28
views
How do I use polymorphism with a generic type who's type argument is a child of the type parameter constraint in c#?
I have a genericType whos type constraint is a base class. When I try to assign a value to this type, using a subclass of the type constraint, it doesn't work.
I understand that the reasoning for this ...
0
votes
0
answers
32
views
typescript infer object value from key
I have a map of components like this:
import { Select, Input, DatePicker } from 'antd';
const MyComponentMap = {
Select,
Input,
DatePicker
}
I'm trying to create a JSON structure like this:
...
0
votes
0
answers
21
views
Differentiating custom Typescript Interfaces that have the same fields
I have a custom interface like this:
interface Pointer<T> {
id: string
}
id is a pointer to other data structures, but the id field doesn't contain information about which data structure it ...
-2
votes
0
answers
50
views
Swift Generics: using the same function with and without generics [closed]
I use the following code to load json mock files into Decodable objects from the project's bundle:
protocol LocalDataProviderType {
func readFromBundle<R: Decodable>(resource: String, type: ...
0
votes
1
answer
34
views
Non-nullable enum as generic parameter [duplicate]
I am trying to implement this helper function in C# 7.3:
public static T? ToEnum<T>(this string enumName)
where T : Enum
=> Enum.TryParse<T>(enumName, out T val) ? val : null;
...
0
votes
1
answer
39
views
+50
What is the best way to work with classes that subclass from Generic types?
Assume we are given a generic class definition such as:
from dataclasses import dataclass
from typing import TypeVar, Generic, List
T1 = TypeVar('T1')
T2 = TypeVar('T2')
@dataclass
class ...
0
votes
1
answer
42
views
In a Java interface, is there a way to return an enum nested in a generic type?
I'm looking for a way to return an Enum type nested in a Generic class. Here's what I mean:
public interface MapperClass<E, D> {
D entityToDto(E entity);
default List<D> ...
0
votes
1
answer
24
views
Map Typescript generic array
Suppose I have an object with a static set of keys, and then a type specifying a subset of those keys as a static array:
const myBigStaticObject = {
key1: () => 'foo',
key2: () => 'bar',
//...