Questions tagged [generics]

22189 questions
1

votes
1

answer
239

Views

Get all properties on a class that are a specific open generic type

If I have the following generic class: public class Gen { public T Value { get; set; } } And a class that uses it: public class Thing { public Gen GenIntProperty { get; set; } public Gen GenStringProperty { get; set; } public string NoGenericProp { get; set; } } Using reflection, how can I get just...
Bradley Uffner
0

votes
1

answer
18

Views

Shouldn't every class that inherits an interface implement all interface members?

What is the difference between ClassTemp1 and ClassTemp2? I thought every class that implements an interface should implement all the interface members but ClassTemp2 has no error. Why? public interface ITemp : IComparable { void Temp(); } public class ClassTemp1 : ITemp // Error { } public class Cl...
Hree
1

votes
1

answer
26

Views

Java 8 wildcard type cannot be instantiated directly

Java 8 here. I have the following generic class: public class Memory { private String moniker; private Date timestamp; private T data; // constructors, getters & setters, etc. } I'm trying to build a non-generic MemoryFactory like so: public class MemoryFactory { public Memory createMemory(Object da...
hotmeatballsoup
1

votes
2

answer
84

Views

How to use Generics or Reflection to show/hide fragments? Kotlin Android

I have a fragment manager to show/hide fragments in my app. Right now when I want to show a fragment from any activity or fragment I call this method from the manager fun show(manager: FragmentManager, fragmentTag: String, container: Int, data: Any?): Companion { var fragment = manager.findFragment...
Pablo R.
1

votes
1

answer
24

Views

Typescript's conditional type based one extends behaves not as expected

Let's say we have this example: class Base {} class ClassA extends Base {} class ClassB extends Base {} type Condition = ClassA extends ClassB ? true : false; The base class has one generic argument which basically says, anything derivind from it should template it with it's own type. Then we have 2...
Maroš Beťko
1

votes
1

answer
47

Views

Design a generic trait in Scala

I'm learning data structure recently. There is a case that I want to design a generic trait which type should support comparable. If I need to design a generic class, I can design like the following: class SortedType [A: Ordering](val x: A) val x = new SortedType(3) val y = new SortedType('Hello, Wo...
xiaojia zhang
1

votes
1

answer
21

Views

Getting the capture of a generic object instance in Java

Java 8 here. I have the following POJOs: public class Fizz { // ctor, getters & setters, etc. } public class Buzz { // ctor, getters & setters, etc. } public class Foobar { // ctor, getters & setters, etc. } public class Envelope { private String name; private PAYLOAD_TYPE payload; // ctor, getters...
hotmeatballsoup
1

votes
2

answer
28

Views

Kotlin generic factory dynamic cast

I want to create factory of objects with generic parameter: interface Foo { fun buzz(param: T) } I have two implementations for tests: class FooImpl1 : Foo { override fun buzz(param: String) { // implementation 1 } } class FooImpl2 : Foo { override fun buzz(param: Int) { // implementation 2 } } Now...
Lau
1

votes
1

answer
38

Views

Private inheritance equivalent in Typescript (Only including or excluding specific class members or properties)

What is the best way to simulate private inheritance in Typescript? Specifically, the chid class wants to hide certain members of a parent class. For example, the expected workaround should achieve the following: Class CustomArray extends from Array, and hides specific members say pop() and shift()...
user3330840
1

votes
2

answer
32

Views

Non-generic method call in Generic class showing “type not valid”

C# 7 I am new to Generics. How do I fix this? On objO = SetPatient(P), I get: P is a type which is not valid in the given context. How do I fix this? TIA public interface IOrderMaker { void SetPatient(IService p); } public class OrderMaker where O : class, IOrderMaker where T : class, O, new() where...
Alan Wayne
1

votes
3

answer
72

Views

How to fix this unchecked cast error when using generics?

In my class I have a list containing TopicNodes. The nodes of those list should extend from the Message class. In the method findNode within the list of nodes there is searched for a node with a specific topic and if it matches it is being returned. The Java compiler complains about the TopicNode be...
Klyner
1

votes
2

answer
41

Views

Problem with adding items to a generic list

I have the following interface public interface IInterface { int GetId(); } ClassA is a generic class but T should implement IInterface public class ClassA where T : IInterface { } ClassB implements IInterface public class ClassB : IInterface { public int GetId() { return 1; } } ClassC is where my p...
user3170354
1

votes
1

answer
41

Views

Dependency Injection: No Service for type

I'm trying to separate the concerns across my application and I thought this answer by Steven fits my scenario beautifully but I'm trying to remove the ninject element: Validation: How to inject A Model State wrapper with Ninject? I've added all required classes from the answer. I've got my service...
Smithy
1

votes
1

answer
620

Views

Unchecked generics warning in Scala?

I've written a NaturalComparator class/object in Java and rewritten it into Scala: https://gist.github.com/319827#file_natural_comparator.scala However, I wonder why I don't need to @SuppressWarnings('unchecked') in the Scala version. (I compile it by fsc -deprecation -unchecked NaturalComparator.sc...
v6ak
1

votes
1

answer
15

Views

Implementing subtypes for interface methods Java

I've been going over Generic classes and methods in Java and came across this question in a past paper I tried implementing the interface and classes proposed in the question, including the refuel method, and found no problem with passing the Car argument as a parameter Motorized interface public in...
Will170393
0

votes
0

answer
20

Views

Convert a generic type constructor to non generic type constructor

For example, I have class class TestClass { } I have some method that receives the constructor of this class. I want to invoke that constructor with some generic parameter without calling MakeGenericType and GetConstructor method again. static void Main() { var ctor = typeof (TestClass).GetConstruc...
User5854
4

votes
1

answer
67

Views

When does type checking happen in Java

I have a question in my homework that looks like this. Which of the following process happens ONLY during compilation time in Java? (i) type inference – inferring the type of a variable whose type is not specified. (ii) type erasure – replacing a type parameter of generics with either Object or...
Ranice Tan
-1

votes
1

answer
24

Views

C#: Generic method expression with unknown signature

For example we have a generic method public void Test(T param, Action callback) { } If call this method with some parameter, it automatically detect the type of T and we don't need to declare it explicitly. For example: // here 'int' detected Test(1, (intVariable) => { }); // here 'string' detected...
Grigor Aleksanyan
1

votes
2

answer
43

Views

Generic type factory within static helper

I'm looking for a way to return a new instance of a type which extends an abstract class in Java, ideally without reflection from a static method. So I want be able to call: SomeClass anInstanceOfSomeClass = Builder.build() I hoped I could do something like: public class Builder { public static T b...
dougajmcdonald
1

votes
3

answer
53

Views

What are the restrictions on generics at inheritance hierarchy?

Suppose there is classes/interfaces hierarchy: class A{ T method(T t){ return t; } } class B extends A{ T method(T t){ // method(T)' in 'B' clashes with 'method(T)' in 'A'; both methods have same erasure, yet neither overrides the other return t; } } As we see there are a compiler error. I've never...
J.J. Beam
1

votes
3

answer
39

Views

Exception handling / suppression with higher order function

I have an application in a micro service architecture. This application is getting data from different sources and is getting a lot of different error-responses from the various of other applications. Some exceptions, like 404-Not found exceptions can be thrown and returned to the end-user, but othe...
Mr.Turtle
1

votes
1

answer
155

Views

Cannot convert value of type 'Int' to expected argument type 'Int' in generic

I've created a simple protocol with a method that takes a generic parameter. protocol NotifyDataSelected: class { func notify(data: T, value:T, at indexPath: IndexPath?) } I've implemented the protocol function as shown below: extension MainButtons: NotifyDataSelected { func notify(data: Int, value:...
Phantom59
1

votes
1

answer
59

Views

How do I sort a list based on its child object attributes?

I'm wondering if someone can elucidate a method to sort a list of objects based on a child object's attribute. I'm working with the following model: public class Content { public string Id { get; set; } public List Attributes { get; set; } } public class ContentAttribute { public string Value { get...
Not_Sure
1

votes
2

answer
41

Views

Passing Type to Method for Use in Generic

I'm trying to understand why the following code does not work and how I need to change it to make it work. In short, I'm trying to pass a Type into the method and then use that Type when declaring List. public void TestMethod(Type type) { List items = new List(); } I get the error: ''type' is a vari...
Kevin
1

votes
1

answer
57

Views

How do I write a generic iterator that keeps a state and returns a value without using clone?

I tried to write a generic iterator, but I do not see how to return value without using clone. Is there any way to create a variable within the next function and return a reference? If I replace T with u32, then I can just return Some(self.count), but using generics, it is not possible. use num_trai...
HamoriZ
1

votes
1

answer
35

Views

Typescript: Exclude<T, K> doesn't exclude my type

I built a function called compact, what this function do is to remove all falsy values in an array. This is the javascript implementation of compact: function compact(arr) { return arr.filter(Boolean); } const MyData = [0, 1, null, 2, undefined, '']; console.log(compact(MyData)) // => [1, 2] This is...
Joseph Wang
1

votes
2

answer
44

Views

In kotlin, what is the proper way to test if a value of a generic type implements an interface, and then use it as that interface?

Given a method which accepts a parameter of a generic type, I would like to check if the type implements Comparable, and if so, compare it with another value. Assuming the type parameter is T, since T is erased, a test of the form t is Comparable is not possible, even with reified type parameters....
abhijat
1

votes
2

answer
43

Views

Moving like methods into generic implementation

I am trying to refactor some code and have to admit that I am new to the concept of generics. I have a base class: BaseVarDef.cs: using UnityEngine; public abstract class BaseVarDef : ScriptableObject { [Multiline] public string DeveloperDescription = ''; public T Value; public void SetValue(T valu...
Timothy McCune
1

votes
2

answer
1.9k

Views

Correct use for avoiding unnecessary casts with generic types (SuppressWarnings unchecked conversion)

There are similar questions out there but I didn't find any that really answers my concerns or that covers my actual implementation. With the following example code (which reflects my actual situation) public class MainTest { public static void main(String[] args) { WhateverDtoXmlParser parser = (ne...
dominicbri7
1

votes
1

answer
13

Views

Typescript Generics wrapper: Untyped function calls may not accept type arguments

This code snippet with Generics works perfectly fine (Link to Simple and Working Code) const state: Record = { isPending: false, results: ['a', 'b', 'c'] } const useValue = (name: string): [T, Function] => { const value: T = state[name] const setValue: Function = (value: T): void => { state[name] =...
Alp
1

votes
2

answer
50

Views

Java Generics: Return a Type of another Type

This could be a possible duplicate to another question here but I've searched but couldn't get the question I wanted. Kindly point me to a similar question if any. Is it possible to return a generic of a generic? Here's what I mean: public T myMethod(Class classT, Class classK) { //...method implem...
Kihats
0

votes
2

answer
263

Views

Can a scala type class have abstract type members?

I have this type class: sealed trait DbValueOps[T Some(new DbString(newContent)) case false => None } def fromString(newContent: String): Option[DbString] = this(newContent) def isValidContent(newContent: String): Boolean = !newContent.isEmpty } } But when trying to use the type class instance with...
Frederik Baetens
0

votes
1

answer
7

Views

Operator < doesn't seem to support “Any” type How to fix it?

The following is a quick-sort function written in Scala to sort a list of mixed types(int, double, float etc.). The error popped out and said in line 3 'Type mismatch, expected: T => Boolean, actual: T => Any Cannot resolve symbol
user132603
1

votes
0

answer
112

Views

Can Java recognize a type parameter, T, as a super type of some class?

Background: I have 3 classes: A, B, C where they all extends 'Super' and implements 'Interface' and I want to write code that only uses only the methods from 'Super' and 'Interface' Unfortunately, I don't have control over the source code of A, B, C, 'Super', 'Interface' to change the inheritance ch...
Sgene9
1

votes
0

answer
87

Views

Mapping generic parameter to compile time data in Typescript?

I'm playing around with trying to disentangle a codebase from Sequelize. Right now we have tons of code like: // Defining interface for model instances interface UserInstance extends Sequelize.Instance { ... database field here ... } // Wrapper class managing connection & model definitions class Db...
Chris Tavares
1

votes
0

answer
55

Views

Unable to Initialize a Generic type with a Generic method parameter

I was fiddling around with generic types in the Swift playgrounds, when I attempted to use the code below: class Node { let value: T init(_ t: T) { self.value = t } func convert(to type: U.Type) -> Node? { guard let new = value as? U else { return nil } return Node(new) } } Note: This code is hypoth...
Caleb Kleveter
1

votes
0

answer
862

Views

Executing MediatR PreProcessor Only for Specific Interface Types (Commands)

[NOTE: This is a 'replacement' question. The first one was based on my main project's code so I've redone the question with code from a single-purpose project that illustrates the principle more cleanly. The question remains the same, just better presented.] The Scenario I'm trying to setup a comman...
platypusjh
1

votes
1

answer
281

Views

Use generic extended swift class in Objective-c

In my project i have many swift classes that extend generic classes. And Now i'm in a need to send data from objective-c class to these swift classes. Is there any possible way to do this ? I have tried using @objc before class as shown below but it didn't allow me to do this. I followed this answer...
Parv Bhasker
1

votes
1

answer
63

Views

How to get the data type in Typescript using Generics

I have a data structure that is built using generics. When I go to populate data though, I want to ensure I can convert some simple formats into the proper types. As the class us configured using Generics, I cannot seem to detect the type of the data in other code. This is a simple example extra...
Steven Scott
1

votes
1

answer
82

Views

Swift 4: generic conforming to AnyObject does not accept a protocol conforming to AnyObject

I need to create an array of type-safe weak references a structure that holds a 'type-safe' weak reference and can be an element of an array: public struct WeakRef: Hashable { public weak var ref: T? public let hashValue: Int init(_ ref: T) { self.ref = ref self.hashValue = ObjectIdentifier(ref).has...
Yaroslav Yaremenko

View additional questions