Questions tagged [type-parameter]
A type parameter is a parameter whose value is a type.
521
questions
2
votes
1
answer
158
views
How to type a custom async Express handler so it's transparently passed the generic typed parameters
My goal is to define a custom Express endpoint wrapper, so it wraps async functions and handlers error accordingly (in the future it might do more stuff).
The handler is pretty basic, and I've defined ...
0
votes
0
answers
36
views
Access Data class property while using Generic Type parameter <T> in runtime [Kotlin]
I'm trying to return a property/value from Data class by checking type parameter
Data Class :
data class SystemConfiguration(
val systemName: String,
val fields: List<String>
)
Abstract ...
-2
votes
1
answer
39
views
Why does this override not compile when <T> is present?
This override does not compile, but when the type parameter T is removed from the overriding method it compiles fine. Why?
class Base {
public <T> Collection<String> transform(...
1
vote
0
answers
41
views
Restrict interface type parameter to class that is implementing the interface
I'd like to create an interface that gives objects of certain classes an id and a dictionary where you can find the reference by Id. So every class should have their own counting id (starting at 1).
...
1
vote
1
answer
27
views
Why is the first type parameter better than the second?
I was going through TS documentation when I came across the section Use Fewer Type Parameters. Here, we are presented with 2 examples:
function filter1<Type>(arr: Type[], func: (arg: Type) => ...
0
votes
1
answer
73
views
Type Arguments and Bounds in Scala
I have the following example:
import scala.concurrent.Future
trait MyTrait[F[_]] {
case class Test[X[_]](x: X[Int])
def test[G[_]]: F[Test[G]]
}
class LocImpl extends MyTrait[Future] {
...
1
vote
1
answer
44
views
Resolving hidden Type Parameter in Java
Consider the following code:
class Scratch<T> {
class InnerClass<T> {
public void executeHiddenMethod(){
//..some code to use Inner (T) type
T r = null; //declared T from ...
2
votes
0
answers
107
views
C# Blazor pass type param to component using a typename supplied as string
I want to pass a type parameter to a Blazor component by supplying it from a list of types.
Component ("TextDataGrid.razor"):
@typeparam TData where TData : ITextData, new()
<!-- ...
0
votes
2
answers
173
views
Type parameter under self-type doesn't conform to upper bound despite evidence
I have a trait with a self-type annotation that has a type parameter. This trait is from a library and cannot be modified. I want to pass this trait to a function that will require an upper bound for ...
0
votes
0
answers
11
views
Mongo Java CodecRegistry lacks the ability to deal with Type Constructors
Let's assume I have multiple collections, each, a variation of a type Event<T>.
However, given the fact that the CodecRegistry works only with Class, which suffers from erasure, That's something ...
0
votes
1
answer
54
views
How can i specify that the type parameters of a class have to inherit the class itself? ( class A<T : A>{ __ } ) | Kotlin
i have an abstract class with a type parameter:
abstract class AClass<T>(){ ___ }
however, i want to specify that the type T must be a child of AClass itself.
abstract class AClass<T : AClass&...
0
votes
0
answers
22
views
Calling .NET DLL function with type parameter from PowerShell [duplicate]
I'm trying to make a PowerShell script using the DocumentFormat.OpenXml library. Everything is working fairly well, except that I'm struggling with syntax for passing type parameters. Specifically, I'...
0
votes
0
answers
32
views
How to pass generic type with extension restraint to a method in C#
I want to pass to the method CreateCell() the Type of a subclass that extends from Cell (in the example ReproducerCell). I am guessing that I should pass the Type itself extracted using typeof(...
0
votes
3
answers
218
views
In java, what is the exact meaning of each type parameter of a generic method in a type introduction?
When we define a generic class, in the type introduction, each type parameter acts as a placeholder for each unique type that will be passed to either the class initializer or a class method. This ...
2
votes
1
answer
42
views
Type Parameter Panicking in Function Call
I have a struct in Go, which represents a state. I now want to be able to compare two states (current & desired),
whereby each field is compared with the other. I define two states as "equal&...
1
vote
1
answer
46
views
is it possible to refer to a type when implementing a function with type parameters in typescript
I want to split the type specification and the implementation of a function in typescript
For example:
If I have a type like this
type MyFuncType = () => void
I can create an implementation that ...
0
votes
1
answer
36
views
Assignment of same generic types with wildcard arguments
Why the following method does not give a compiler error? :
public void func3(List<? extends Number> l1, List<? extends Number> l2) {
l1 = l2;
}
Run-time error could ...
0
votes
1
answer
20
views
Is there any difference in Kotlin between a capped type parameter extension function and a normal extension function?
Is there any difference between these two?
fun <T : Parent> T.function() {}
vs.
fun Parent.function() {}
0
votes
0
answers
115
views
In Java why aren't functions by default covariant with the return types and contravariant with the parameter type
Take a look at the following code
If Functions were contravariant with the parameter type, this would work, since they are not, the compiler complains:
// contravariant with the parameter type
...
2
votes
2
answers
721
views
What are the benefits of replacing an interface argument with a type parameter?
Defining an interface type to type parameters like this:
func CallByteWriterGen[W io.ByteWriter](w W, bytes []byte) {
_ = w.WriteByte(bytes[0])
}
...causes extra pointer dereference through ...
0
votes
1
answer
60
views
Generic Constraint Contravariant Incompatibility in TypeScript
I'm trying to model tagged unions as data.
First I create a Tagged utility type, to represent anything intersected with the tag field:
type Tagged<T, With extends PropertyKey> = T & { _tag: ...
0
votes
0
answers
40
views
Is it possible to have a new type parameter for a method of a parameterized type in Go? [duplicate]
I'm trying to write a generic List container in Go so I can better learn how type parameters work.
Currently I'm working on a Map method that takes in a mapper function and returns a new list that has ...
0
votes
1
answer
32
views
Why does typescript allow this kind of circular reference when using generic types?
Why does typescript not complain about the definition of the Document interface below. It seems like a circular reference. How can a type parameter of "Document" be supplied while writing ...
-2
votes
2
answers
52
views
Is there any way for generics themselves to take type parameters in Java?
Let's say I have a function with the following signature:
<T> T f(List<T> a, T b)
Obviously, I can do the following:
List<Integer> list = new ArrayList<Integer>();
int x = 0;
...
1
vote
2
answers
677
views
An issue with Generic type parameters and Inheritance
Couldn't concretize the title, sorry for that.
For example, we have a Parent class and a Child class:
package test;
public class Parent {
}
package test;
public class Child extends Parent {
}
And ...
3
votes
2
answers
4k
views
Can I construct a slice of a generic type with different type parameters?
In the following code I have a token type that contains a literal value. By using an empty interface I can create a slice of tokens and append tokens that have different types. I don't think it's ...
12
votes
1
answer
9k
views
How to solve "interface method must have no type parameters"? [duplicate]
I'm trying out go generics in 1.18beta2 and I'm trying to write an abstraction layer for key/value store, boltdb. This is what I'm trying to achieve with it.
type Reader interface {
Read(bucket []...
15
votes
1
answer
12k
views
interface contains type constraints: cannot use interface in conversion
type Number interface {
int | int64 | float64
}
type NNumber interface {
}
//interface contains type constraints
//type NumberSlice []Number
type NNumberSlice []NNumber
func main() {
var b ...
3
votes
1
answer
680
views
What's the difference between a generic slice argument and an argument constrained to slice types?
Consider the experimental package slices. The package is experimental, so I understand the signatures may change; I'm using it to illustrate the issue.
Consider the signatures of two functions from ...
0
votes
2
answers
250
views
Method 'read' overrides nothing
I am new to Scala Type Parameter
Below is the scala code,
trait Pet {
val name: String
}
class Cat(val name: String) extends Pet
class Dog(val name: String) extends Pet
trait Reader[T &...
0
votes
0
answers
48
views
When type arguments are supplied for the constructor - then Diamond Operator cannot be used and Type Arguments must be supplied? [duplicate]
Consider the following clause from the JLS (§15.9)
It is a compile-time error if a class instance creation expression provides type
arguments to a constructor but uses the diamond form for type ...
0
votes
1
answer
45
views
How to define a type parameter inside a type parameter in java generics
I have a message dto
class MyMessage<T>{
T payload;
String groupId;
}
I have an interface that has a simple implementation
interface Sender<T>{
void sendMessage(T message);
}
...
6
votes
3
answers
227
views
Java Generics: What is the benefit of using wildcards here?
The Collections.fill method has the following header:
public static <T> void fill(List<? super T> list, T obj)
Why is the wildcard necessary? The following header seems to work just as ...
2
votes
1
answer
357
views
Is there a shorthand for AsRef<T> in Rust?
Is there suggar for AsRef? Preferably in the stable channel.
I'm frequently declaring string-like parameters with as ref to make it easier to interop with various incantations of strings (String, &...
0
votes
3
answers
984
views
Optional generic type Parameter for fn?
I would like a function to have an optional generic type Parameter to do something like this:
fn main() {
bar::<()>();
}
fn bar<F: Foo>() {
let x = some_computation();
if F != ...
1
vote
0
answers
34
views
"Blank" Generic Type Parameters - Use cases and explanation [duplicate]
In an example project (https://github.com/dotnet-architecture/eShopOnContainers) I saw that, during service registration, the author of the code was able to register a service with blank type ...
3
votes
0
answers
120
views
scala case class with type parameter got confusing "type mismatch" compile time error
I have case class ValueContainer with two operations, removeFirst fails
with:
type mismatch;
found : Option[T(in class ValueContainer)]
required: Option[T(in method removeFirst)]
def ...
0
votes
1
answer
92
views
In C#, is it possible to create a generic method for instantiating multiple "manager clients" generated from Praxedo WSDL?
We are using Praxedo for multiple services, many of which are on different SOAP APIs which are never-the-less similar to instantiate and consume.
Rather than repeating code, I'd like to make a generic ...
1
vote
2
answers
618
views
In C#, How can I dynamically pass T into services.AddHostedService<T>()?
I have a webservice with multiple hosted services.
I want to be able to turn them on and off through "appSettings.json".
In "StartUp.cs", I populate an instance of
public class ...
6
votes
1
answer
797
views
In Rust, how can I restrict a generic T to allow modulus?
As an exercism exercise, I'm currently trying to filter an iterator according to whether the value is even in order to produce a new iterator.
My function currently looks like:
pub fn evens<T>(...
0
votes
0
answers
20
views
Parametrized type compiler bug or proper program?
I'm surprised this program compiles. I would think the strLengthOne declaration/initialization line would be flagged as a type error. Should not T describe different types for the two different ...
1
vote
0
answers
134
views
haxe get type info for fields of a function type parameter
Reflect can list an object's fields at runtime, but doesn't have type info. rtti has type info, but doesn't seem to work for type parameters.
In this example, I want MyLibrary to be able to figure out ...
1
vote
1
answer
715
views
TypeScript - How do you chain accessing optional nested type properties?
I have a Client class that stores caches of other objects that the application needs to keep in memory. The structure of the object's cache is developer-defined. For example, if we have a cache of ...
1
vote
1
answer
125
views
Classic "omit" function, similar code totally different typing results when written the usual way and when written with currying, what did I miss?
Ok so I was trying to write a type-aware "omit" function.
After a long, long reading of stack-overflow I came up with the following solution that works (yay):
const omit = <
T extends ...
3
votes
1
answer
58
views
How can I get this method to infer type argument from usage?
I would like to get TryGet method to infer the type argument, just as it is possible for TrySet:
private void Test()
{
TryGet<int>(RefProperty, s => s.GetInt); // works fine
TryGet(...
0
votes
1
answer
287
views
Rust limit generic parameter of generic parameter
I've defined a trait Node<T: Ord + Eq + std::fmt::Debug> to provide standard operations for a tree's node - I was originally using an enum, but I'm thinking that this approach will be a bit more ...
0
votes
0
answers
15
views
Java Type Parameter - assigning new type parameter compiles [duplicate]
Learning Java here, and specifically about type parameter. Can you explain to me why this code compiles?
public static void main(String args[]){
bar a = new bar( 1);
System.out.println(a....
1
vote
0
answers
292
views
Rules of thumb of when to include angle brackets <...> for template class
For the class template, what are the rules of thumb to include <type_parameter>? For example, we have the following template class List as a quick example I just coded up:
template <class T&...
1
vote
1
answer
117
views
Question about Scala implicits with multiple type parameters
I am having a hard time understanding an error related to "could not find value for implicits" error. Here is a minimal example to highlight the error.
sealed trait BehaviourA
final case ...
0
votes
1
answer
56
views
Can't resolve the implicit for a constrained class type parameter
package ir.ashkan.shahnameh
object Implicit {
sealed trait A
class B extends A
class C extends A
def listOf[T <: A](implicit ts: List[T]): List[T] = ts
class Module[T <: A] {
...