Questions tagged [generics]

18555 questions
10

votes
2

answer
184

Views

Why does this code fail to compile, citing type inference as the cause?

Here's a minimal example of the code I'm working with: public class Temp { enum SomeEnum {} private static final Map TEST = new EnumMap( Arrays.stream(SomeEnum.values()) .collect(Collectors.toMap(t -> t, a -> ""))); } The compiler output is: Temp.java:27: error: cannot infer type arguments for EnumM...
tterrag
1

votes
2

answer
322

Views

How can I specify a generic type on an overloaded operator in Kotlin?

I'm looking to overload the division operator, "/", but would like to allow for a generic type to be specified to guide the type of the return value. Here's an example: inline operator fun MyType.div(fieldName: String): T { val value = someFunction(fieldName) return convertToExpectedValue(value) }...
cmorriss
0

votes
0

answer
27

Views

How to reduce code with generics and probably reflection

I have DTO objects, then I need to sort the collection of objects dynamically, kind of like a database ORDER BY, but I do not have a database to actually make the queries do the actual work (I know, but it is what I have today...). It seems to me that the StatusComparator and TypeComparator should...
Schenz
0

votes
1

answer
37

Views

iterating through generic type T if T is IEnumerable without cast

The following code would compile if foo is casted to either a type implementing IEnumerable or dynamic. Is there a way to achieve the same without casting foo ? I am aware I could do two methods and don't wish to force more constraint to T. interface IDummy {} class FooBar where T : class { void Ba...
Baguette
1

votes
1

answer
72

Views

Typescript Generics: return instance of class parameter

I have a data store and want to create a method to load data from the store. The store contains different types (classes) of data. Let's say my store contains (among other) data of type Author. I want to load author with id 1: const author1 = store.loadById(Author, 1); Now how do I have to use gener...
mvermand
1

votes
2

answer
177

Views

How do you define an array of generics in TypeScript?

Let's say I have a generic interface like the following: interface Transform { transformer: (input: string, arg: ArgType) => string; arg: ArgType; } And then I want to apply an array of these Transform to a string. How do I define this array of Transform such that it validates that is equivalent in...
user1084447
1

votes
2

answer
54

Views

Check that object is one of many types in Kotlin

I have the following classes: sealed class A : BaseType sealed class B : BaseType sealed class C : BaseType ... If I then have a processObject method that looks like this: fun processObject(obj: BaseType): Int { return when(obj) { is A -> 1 is B -> 1 else -> 0 } } I notice that I am now repeating my...
Arnab Datta
1

votes
1

answer
45

Views

PECS For generics in Non Collections

Joshua Bloch came up with the PECS, which says the rule when to use ? extends T and ? super T. If you think about PECS in terms of Collections framework, then it is very straightforward. If you add values to the data structure, use ? super T. If you read from the data structure, use ? extends T. fo...
Fatih Arslan
1

votes
1

answer
49

Views

Java generics upper bounded wildcard restriction

Can someone explain what's the difference between these two snippets of code ? 1) private Collection getAnimal() { return null; } 2) private Collection
Martin Čuka
1

votes
1

answer
38

Views

Scala generics: type mismatch with folding

New to scala. Trying to understand why scala compiler is not happy about the below: sealed trait LinkedList[A] { def fold[B](end: B)(func: (A, B) => B): B = this match { case End() => end case Pair(hd, tl) => func(hd, tl.fold(end)(func)) } def sum: Int = fold[Int](0){(hd, tl) => hd + tl} } final cas...
Pritam
0

votes
0

answer
24

Views

Improving performance of generic conversion from DataRow to T

When querying more than 10k data sets from a MSSQL database our software gets pretty slow (more than 10sec loading time). I digged deeper just to find out that they implemented some Entity-like generic object conversion from DataRow to T by calling the contructor of the target type which accepts a D...
spcial
1

votes
1

answer
1.1k

Views

Calling method with generic type using class name as string [duplicate]

This question already has an answer here: Calling a function from a string in C# 6 answers Having this class : class ClassA{ } and a method with this signature: void MyMethod(); All we use it on this way: MyMethod(); But... exist some chance of call MyMethod having the class name as string?. I.e.:...
Sebastián Guerrero
1

votes
2

answer
135

Views

C++ typecast overloading

Supposed I have a class like this: template class Vector2 { public: Vector2(const T a, const T b) : x(a), x(b) {} T x; T y; } I want to be able to do something like this: const Vector2 d(31.4, 48.2); // note the const!!! Vector2 i = static_cast(d); // i.x == 31 // i.y == 48 I have tried overloading...
Charles
1

votes
1

answer
546

Views

Extending the SequenceType in Swift

I wondered why map() and filter() in SequenceType return both an Array. Actually, I don't think that's necessary. Returning a sequence again feels much more sensible to me. However, I got stuck when trying to add sequential versions. Here's my attempt with map: extension SequenceType { func seqMap(...
obecker
1

votes
2

answer
73

Views

Differences between generic methods in java

Suppose I have this interface: public interface Lookup { public T find(String name); } Are there differences between the following methods? 1) public void process(String name, Lookup table) { System.out.println(table.find(name)); } 2) public void process(String name, T table) { System.out.println(...
Jordan
1

votes
2

answer
994

Views

Type parameter bounds - Unchecked overriding: return type requires unchecked conversion

How can I get rid of warning Unchecked overriding: return type requires unchecked conversion. Found 'org.example.AAndB', required 'T'. in following code. I try to design an interface (Interface) in such a way that it wouldn't explicitly state return type of method get() (AAndB) but rather enumerate...
czerny
1

votes
1

answer
223

Views

Convert a generic IEnumerable<T> to IEnumerable<KeyValuePair> (C#)

In the following code, I need to explicitly mention CountryId and CountryName but I would like to avoid that and trying to create a generic method. public struct KeyValueStruct { public int Key { get; set; } public string Value { get; set; } } private static IEnumerable ConvertPocoToKeyValueList(IEn...
Coder Absolute
2

votes
2

answer
19

Views

Why do I need to force cast a property to a generic method with the same signature as the property?

This is my code: class GenericClass { let enumProperty = SomeEnum.myValue enum SomeEnum { case myValue } func callOtherClass() { OtherClass.handle(property: enumProperty) // Compile error } } class OtherClass { static func handle(property: GenericClass.SomeEnum) {} } Why do I get the compile error:...
J. Doe
1

votes
3

answer
465

Views

Extending a Collection where the Element type is generic (Swift)

It's simple to extend a Collection type in swift to have a custom function for particular Element types: struct MyStruct { let string: String } extension Set where Element == MyStruct { func getFirstWith(string: String) -> Element? { return filter({ $0.string == string }).first } } But suppose your...
David Coufal
1

votes
2

answer
55

Views

static/non-static innerclass : The type parameter T is hiding the type T

When I use static nested class, I don't get the warning The type parameter T is hiding the type T. However, when I use the non-static nested class I get the warning. public class CustomStack { private class CustomNode{ private T data; private CustomNode next; public CustomNode(T data){ this.data = d...
John Rambo
1

votes
1

answer
120

Views

How do I write a generic Swift extension to deep merge two dictionaries?

I'm trying to write a function to deep merge two dictionaries. By this I mean that when the values for a key in both dictionaries are being merged and those values are both dictionaries, they will be merged instead of one being replaced by the other. Here's what I have: extension Dictionary { public...
Hilton Campbell
1

votes
2

answer
362

Views

How to create instance of generic class passing a method reference in constructor with kotlin

Now that I'm using kotlin as my main programing language I'm trying to simplify Android's Recyclerview implementation logic and I'm stuck at following point: Let's say I have defined the following ViewHolder class, where a click position event is propagated via a method reference in the constructor....
Pablo A. Martínez
1

votes
1

answer
261

Views

Kotlin generics expecting unexpected type

I've defined the following base class with two generic types and using it two levels deep (for lack of a better phrase). Here's my use case. abstract class BasePresenter { var model: M? = null var view: WeakReference? = null fun setM(model: M?): Unit { this.model = model if (setupDone()) { updateVie...
Rafa
1

votes
1

answer
378

Views

How to flatten the generic types declaration in typescript?

Case: A function input a nested generic object, and output flat object like follow: interface Deep { p1: T; p2: T; } type Nested = { [P in keyof T]: Deep; } type Flat = { [P in keyof T]: T[P]?; } function flat(input: T, p: keyof Deep): Flat { const put: any = {} for (let k in input) put[k] = input[k...
kcats
1

votes
1

answer
93

Views

Short hand (1 line statement) to initialize array of generics

I was wondering, is there any short hand to initialize array of generic? Currently, the way to initialize array of non generics is as follow. String[] s = { "hello", "world" }; However, it is not possible to perform the similar, for generics. Call calls[] = { yearlyFundamentalResponseCall, quarterly...
Cheok Yan Cheng
1

votes
1

answer
160

Views

Does Kotlin have any generic constraints other than upper bounds?

https://kotlinlang.org/docs/reference/generics.html#generic-constraints says The most common type of constraint [on a type parameter] is an upper bound but doesn't list any others. Are there any other constraints on type parameters supported in Kotlin, or planned in future (except for type classes,...
Alexey Romanov
1

votes
1

answer
46

Views

Typescript: constrain argument of function to be a key of an object associated with a value of a particular type

Is there a way to make the following type check? function getNumberFromObject(obj: T, key: keyof T): number { return obj[key] // ERROR: obj[key] might not be a number } I want to specify that key should not only be a key of T, but a key with a number value.
Lionel Tay
1

votes
1

answer
90

Views

Cannot convert value of type 'String' to expected argument type '_?'

So I'm struggling with Swift generics. I'm trying to create an instance of a struct that is defined in a different module. The struct has a generic type for it's property. Module code: public struct MyModuleResponse { let payload: T? } Main target code: @import MyModule .... let payload = "Something...
Camsoft
1

votes
2

answer
48

Views

Inheriting static protected inner class, wrong complaint by javac

Consider this code: Base.java package package1; public class Base{ protected static class Inner{} } Derived.java package package2; public class Derived extends Base{ static class Inner extends Base.Inner{} } The base class compiles without problems. The compilation of the derived class fails, the fi...
Sergey S.
1

votes
1

answer
25

Views

Implement PAT for a certain associated type

Assume, you have a PAT: protocol PAT { associatedtype T func provide() -> T } And another protocol, that uses that protocol as a type constraint: protocol RegularProtocol { func consume(_ pat: P) -> P.T } Is there a way to implement that second protocol for a certain associated type of PAT? For exam...
LilKitty
1

votes
3

answer
37

Views

Re-create (generic) member and populate/assign field member(s) via Java reflection

I have a set of classes with any number of non-custom members — just primitives, wrappers, etc.; some of them can be annotated with @Encrypted in order to be processed differently. All types implement Envelope. I'm creating two Maps (based on a given type), storing the "field name" (as the key) an...
x80486
1

votes
3

answer
129

Views

decoding a json to generic array or class in swift

How do you decode json to a generic model in swift? In java for decoding json I use GSON and in general it does not matter I use or ArrayList.In swift Array is a struct and can't be inheritance and it has not implemented Decodable. I'm looking for a generic elegant class to use in all my web servic...
naser khsoravi
1

votes
2

answer
38

Views

Creating a type that takes enum argument

I am trying to create a reusable type utilizing the Record type. enum MyKeys { ALPHA = 'ALPHA', BETA = 'BETA', GAMMA = 'GAMMA', } interface MyValues { in: any[]; out: any[]; } type Case = Record; Ideally I can use Case instead of Record. Type 'T' does not satisfy the constraint 'string | number | s...
ThomasReggi
1

votes
1

answer
46

Views

How to fix Cast errors when casting down generic parameters

In some situations I need to cast down an object to an interface to fit my needs, which implicitly requires to cast down type arguments of generic interfaces. Example ICage is the interface for a Cage of an animal of type IAnimal public interface ICage where TAnimal : IAnimal public class Cage : ICa...
Hakim
1

votes
2

answer
87

Views

Possible eclipse bug

Good day, I'm trying to get my head around a generic-type problem. But it seems like eclipse is complaining while there isn't a valid complaint. consider the following methods public static List
n247s
1

votes
3

answer
78

Views

Create a multidimensional generic array of Optionals

I want to create a two-dimensional array (yes I know that this is actually an array of arrays) holding Optionals. The normal approach for generic array creation does not work though as it fails with a ClassCastException. Here is my code: @SuppressWarnings("unchecked") Optional[][] arr = (Optional[][...
Vajk
1

votes
1

answer
24

Views

Generic interface extending parameterized interface in TypeScript

I have types like this where I overwrite single type while extending interface: type Omit = Pick; interface HTMLEvent extends Omit { target: T; } and now I want to create type EventType that will accept Event type for instance MouseEvent and target type. I've tried this: interface EventType extends...
jcubic
1

votes
3

answer
1.6k

Views

Using generic Dictionary over wcf: what do I need to look for?

Suppose I have a WCF service and a method in the contract _ Interface IThingService '... _ Function GetThing(thingId As Guid) As Thing End Interface where Thing is an ordinary class with ordinary properties, except for one member: Public Class Thing ' ... Public Property Photos() As Dictionary(Of S...
Patrick Szalapski
1

votes
2

answer
568

Views

Sorting Winforms TreeView in a type safe way?

Is it possible to sort a TreeView collection using IComparer and not IComparer? After all they are all TreeNode values, right?
Joan Venge
2

votes
0

answer
19

Views

Typescript: Why is an omitted generic type an object?

I wondering why is the default generic type an object {} and not any? It behaves like an any, but is a bit confusing. Example / Demo class Foo {} // The type of this: const foo = new Foo(); // is {} but expected any or error. I could use: class Foo {} But I want to know the background behind. I thin...
Dominik

View additional questions

Смотреть фильмы онлайн бабушка легкого поведения 2 фильм бесплатно