Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 27/41 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • How do I make lambda functions generic in Scala?

    - by Electric Coffee
    As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method... making the 'def' kind generic is fairly straight forward def someFunc[T](a: T) { // insert body here what I'm having trouble with here is how to make the following generic: val someFunc = (a: Int) => // insert body here of course right now a is an integer, but what would I need to do to make it generic? val someFunc[T] = (a: T) => doesn't work, neither does val someFunc = [T](a: T) => Is it even possible to make them generic, or should I just stick to the 'def' variant?

    Read the article

  • Trouble swapping values as keys in generic java BST class

    - by user1729869
    I was given a generic binary search tree class with the following declaration: public class BST<K extends Comparable<K>, V> I was asked to write a method that reverses the BST such that the values become the keys and keys become values. When I call the following method (defined in the class given) reverseDict.put(originalDict.get(key), key); I get the following two error messages from Netbeans: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: BST.put And also: no suitable method found for put(V,K) method BST.put(BST<K,V>.Node,K,V) is not applicable (actual and formal argument lists differ in length) method BST.put(K,V) is not applicable (actual argument V cannot be converted to K by method invocation conversion) where V,K are type-variables: V extends Object declared in method <K,V>reverseBST(BST<K,V>) K extends Comparable<K> declared in method <K,V>reverseBST(BST<K,V>) From what the error messages are telling me, since my values do not extend Comparable I am unable to use them as keys. If I am right, how can I get around that without changing the class given (maybe a cast)?

    Read the article

  • How to find the class object of Java generic type?

    - by Samuel Yung
    Assume I have a generic type P which is an Enum, that is <P extends Enum<P>>, and I want to get the Enum value from a string, for example: String foo = "foo"; P fooEnum = Enum.valueOf(P.class, foo); This will get a compile error because P.class is invalid. So what can I do in order to make the above code work?

    Read the article

  • Compile time error: cannot convert from specific type to a generic type

    - by Water Cooler v2
    I get a compile time error with the following relevant code snippet at the line that calls NotifyObservers in the if construct. public class ExternalSystem<TEmployee, TEventArgs> : ISubject<TEventArgs> where TEmployee : Employee where TEventArgs : EmployeeEventArgs { protected List<IObserver<TEventArgs>> _observers = null; protected List<TEmployee> _employees = null; public virtual void AddNewEmployee(TEmployee employee) { if (_employees.Contains(employee) == false) { _employees.Add(employee); string message = FormatMessage("New {0} hired.", employee); if (employee is Executive) NotifyObservers(new ExecutiveEventArgs { e = employee, msg = message }); else if (employee is BuildingSecurity) NotifyObservers(new BuildingSecurityEventArgs { e = employee, msg = message }); } } public void NotifyObservers(TEventArgs args) { foreach (IObserver<TEventArgs> observer in _observers) observer.EmployeeEventHandler(this, args); } } The error I receive is: The best overloaded method match for 'ExternalSystem.NotifyObservers(TEventArgs)' has some invalid arguments. Cannot convert from 'ExecutiveEventArgs' to 'TEventArgs'. I am compiling this in C# 3.0 using Visual Studio 2008 Express Edition.

    Read the article

  • c# template member functions

    - by user3730583
    How can I define a template member function in C# For instance I will fill any collection which supports an Add(...) member function, please check out the sample code below public class CInternalCollection { public static void ExternalCollectionTryOne<T<int>>(ref T<int> ext_col, int para_selection = 0) { foreach (int int_value in m_int_col) { if (int_value > para_selection) ext_col.Add(int_value); } } public static void ExternalCollectionTryTwo<T>(ref T ext_col, int para_selection = 0) { foreach (int int_value in m_int_col) { if (int_value > para_selection) ext_col.Add(int_value); } } static int[] m_int_col = { 0, -1, -3, 5, 7, -8 }; } The ExternalCollectionTryOne<...(...) would be the preferred kind, because the int type can be explicit defined, but results in an error: Type parameter declaration must be an identifier not a type The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) The ExternalCollectionTryTwo<...(...) results in an error: 'T' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)... I hope the problem is clear – any suggestions? ----------------------------- edit -------------------------- The answers with the interface ICollection<.. without a template member works fine and thanks all for this hint, but I still cannot define successfully a member template(generic) function So a more simpler example ... how can I define this public class CAddCollectionValues { public static void AddInt<T>(ref T number, int selection) { T new_T = new T(); //this line is just an easy demonstration to get a compile error with type T foreach (int i_value in m_int_col) { if (i_value > selection) number += i_value; //again the type T cannot be used } } static int[] m_int_col = { 0, -1, -3, 5, 7, -8 }; }

    Read the article

  • Type-safe generic data structures in plain-old C?

    - by Bradford Larsen
    I have done far more C++ programming than "plain old C" programming. One thing I sorely miss when programming in plain C is type-safe generic data structures, which are provided in C++ via templates. For sake of concreteness, consider a generic singly linked list. In C++, it is a simple matter to define your own template class, and then instantiate it for the types you need. In C, I can think of a few ways of implementing a generic singly linked list: Write the linked list type(s) and supporting procedures once, using void pointers to go around the type system. Write preprocessor macros taking the necessary type names, etc, to generate a type-specific version of the data structure and supporting procedures. Use a more sophisticated, stand-alone tool to generate the code for the types you need. I don't like option 1, as it is subverts the type system, and would likely have worse performance than a specialized type-specific implementation. Using a uniform representation of the data structure for all types, and casting to/from void pointers, so far as I can see, necessitates an indirection that would be avoided by an implementation specialized for the element type. Option 2 doesn't require any extra tools, but it feels somewhat clunky, and could give bad compiler errors when used improperly. Option 3 could give better compiler error messages than option 2, as the specialized data structure code would reside in expanded form that could be opened in an editor and inspected by the programmer (as opposed to code generated by preprocessor macros). However, this option is the most heavyweight, a sort of "poor-man's templates". I have used this approach before, using a simple sed script to specialize a "templated" version of some C code. I would like to program my future "low-level" projects in C rather than C++, but have been frightened by the thought of rewriting common data structures for each specific type. What experience do people have with this issue? Are there good libraries of generic data structures and algorithms in C that do not go with Option 1 (i.e. casting to and from void pointers, which sacrifices type safety and adds a level of indirection)?

    Read the article

  • Passing the Class<T> in java of a generic list?

    - by Rob Stevenson-Leggett
    I have a method for reading JSON from a service, I'm using Gson to do my serialization and have written the following method using type parameters. public T getDeserializedJSON(Class<T> aClass,String url) { Reader r = getJSONDataAsReader(url); Gson gson = new Gson(); return gson.fromJson(r, aClass); } I'm consuming json which returns just an array of a type e.g. [ { "prop":"value" } { "prop":"value" } ] I have a java class which maps to this object let's call it MyClass. However to use my method I need to do this: RestClient<ArrayList<MyClass>> restClient = new RestClient<ArrayList<MyClass>>(); ArrayList<MyClass> results = restClient.getDeserializedJSON(ArrayList<MyClass>.class, url); However, I can't figure out the syntax to do it. Passing just ArrayList.class doesn't work. So is there a way I can get rid of the Class parameter or how do I get the class of the ArrayList of MyClass?

    Read the article

  • Can I pass a non-generic type where a generic type is expected?

    - by Water Cooler v2
    I want to define a set of classes that collect and persist data. I want to call them either on-demand basis, or in a chain-of-responsibility fashion, as the caller pleases. To support the chaining, I have declared my interface like so: interface IDataManager<T, K> { T GetData(K args); void WriteData(Stream stream); void WriteData(T data, Stream stream); IDataCollectionPolicy Policy; IDataManager<T, K> NextDataManager; } But the T's and K's for each concrete types will be different. If I give it like this: IDataManager<T, K> NextDataManager; I assume that the calling code will only be able to chain types that have the same T's and K's. Is there a way I can have it chain any type of IDataManager? One thing that occurs to me is to have IDataManager inherit from a non-generic IDataManager like so: interface IDataManager { } interface IDataManager<T, K>: IDataManager { T GetData(K args); void WriteData(Stream stream); void WriteData(T data, Stream stream); IDataCollectionPolicy Policy; IDataManager NextDataManager; } Is this going to work?

    Read the article

  • What's my best approach on this simple hierarchy Java Problem?

    - by Nazgulled
    First, I'm sorry for the question title but I can't think of a better one to describe my problem. Feel free to change it :) Let's say I have this abstract class Box which implements a couple of constructors, methods and whatever on some private variables. Then I have a couple of sub classes like BoxA and BoxB. Both of these implement extra things. Now I have another abstract class Shape and a few sub classes like Square and Circle. For both BoxA and BoxB I need to have a list of Shape objects but I need to make sure that only Square objects go into BoxA's list and only Circle objects go into BoxB's list. For that list (on each box), I need to have a get() and set() method and also a addShape() and removeShape() methods. Another important thing to know is that for each box created, either BoxA or BoxB, each respectively Shape list is exactly the same. Let's say I create a list of Square's named ls and two BoxA objects named boxA1 and boxA2. No matter what, both boxA1 and boxA2 must have the same ls list. This is my idea: public abstract class Box { // private instance variables public Box() { // constructor stuff } // public instance methods } public class BoxA extends Box { // private instance variables private static List<Shape> list; public BoxA() { // constructor stuff } // public instance methods public static List<Square> getList() { List<Square> aux = new ArrayList<Square>(); for(Square s : list.values()) { aux.add(s.clone()); // I know what I'm doing with this clone, don't worry about it } return aux; } public static void setList(List<Square> newList) { list = new ArrayList<Square>(newList); } public static void addShape(Square s) { list.add(s); } public static void removeShape(Square s) { list.remove(list.indexOf(s)); } } As the list needs to be the same for that type of object, I declared as static and all methods that work with that list are also static. Now, for BoxB the class would be almost the same regarding the list stuff. I would only replace Square by Triangle and the problem was solved. So, for each BoxA object created, the list would be only one and the same for each BoxB object created, but a different type of list of course. So, what's my problem you ask? Well, I don't like the code... The getList(), setList(), addShape() and removeShape() methods are basically repeated for BoxA and BoxB, only the type of the objects that the list will hold is different. I can't think of way to do it in the super class Box instead. Doing it statically too, using Shape instead of Square and Triangle, wouldn't work because the list would be only one and I need it to be only one but for each sub class of Box. How could I do this differently and better? P.S: I could not describe my real example because I don't know the correct words in English for the stuff I'm doing, so I just used a box and shapes example, but it's basically the same.

    Read the article

  • Visual Studio 2008 having problems with namespaces when used as type in Generic coolection

    - by patrick
    I just upgraded last week from Visual Studio 2005 to 2008. I am having an issue with compiler resolving namespaces when I use a class as a type in a Generic collection. Intellisense recognizes the class and the compiler generates no errors when I use the class except when it is a type in a Generic collection declaration either as return type for a Property or as a parameter to a method. This is happening in my only project that is targeting the 3.5 framework, but changing the project containing the class to use the 3.5 framework doesn't fix the problem. Examples Compile fine MyClass myClass = new MyClass(); SortedList <DateTime,MyClass> listOfClasses = new SortedList<DateTime,MyClass> Compile error - Namespace could not be found public SortedList<DateTime,MyClass> ClassList { get; set; } private void DoSomethingToLists(SortedList<DateTime,MyClass> classList) Intellisense has no problem resolving the namespace, only the compiler. Is this a known bug or am I missing something obvious? Will SP1 fix it? I was able to create a new library containing just this class targeting 3.5 and am now able to successfully use this in both 3.5 and 2.0 projects. My guess is that even though I tried to change the target of my original library, since it was still referencing 2.0 projects there was some conflict.

    Read the article

  • C# specifying generic delegate type param at runtime

    - by smerlin
    following setup, i have several generic functions, and i need to choose the type and the function identified by two strings at runtime. my first try looked like this: public static class FOOBAR { public delegate void MyDelegateType(int param); public static void foo<T>(int param){...} public static void bar<T>(int param){...} public static void someMethod(string methodstr, string typestr) { MyDelegateType mydel; Type mytype; switch(typestr) { case "int": mytype = typeof(int); break; case "double": mytype = typeof(double); break; default: throw new InvalidTypeException(typestr); } switch(methodstr) { case "foo": mydel = foo<mytype>; //error break; case "bar": mydel = bar<mytype>; //error break; default: throw new InvalidTypeException(methodstr); } for(int i=0; i<1000; ++i) mydel(i); } } since this didnt work, i nested those switchs (a methodstr switch inside the typestr switch or viceversa), but that solution is really ugly and unmaintainable. The number of types is pretty much fixed, but the number of functions like foo or bar will increase by high numbers, so i dont want nested switchs. So how can i make this working without using nested switchs ?

    Read the article

  • Why can I derived from a templated/generic class based on that type in C# / C++

    - by stusmith
    Title probably doesn't make a lot of sense, so I'll start with some code: class Foo : public std::vector<Foo> { }; ... Foo f; f.push_back( Foo() ); Why is this allowed by the compiler? My brain is melting at this stage, so can anyone explain whether there are any reasons you would want to do this? Unfortunately I've just seen a similar pattern in some production C# code and wondered why anyone would use this pattern.

    Read the article

  • How to make TObjectDictionary.Values accessible as property?

    - by Holgerwa
    I have an object like this: TMyObj = class private FObjList: TObjectDictionary <integer, TMyObject>; public constructor Create; destructor Destroy; // How to access Values correctly? Something similar to this not working code property Values: TValueCollection read FObjList.Values write FObjList.Values; end; var MyObj: TMyObj; To access the values of FObjList, I'd like to write: for tmpObject in MyObj.Values do ... How do I need to declare the property "Values" so that MyObj.Values behaves exactly as if I would access MyObj.FObjList.Values?

    Read the article

  • Creating a sort function for a generic list

    - by Andrey
    I have a method for sorting generic lists by the object fields: public static IQueryable<T> SortTable<T>(IQueryable<T> q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int?)) { var x = Expression.Lambda<Func<T, int?>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int)) { var x = Expression.Lambda<Func<T, int>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(DateTime)) { var x = Expression.Lambda<Func<T, DateTime>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } // many more for every type return q; } Is there any way I can collapse those ifs to a single generic statement? The main problem is that for the part Expression.Lambda<Func<T, int>> I am not sure how to write it generically.

    Read the article

  • C#, Generic Lists and Inheritance

    - by Andy
    I have a class called Foo that defines a list of objects of type A: class Foo { List<A> Items = new List<A>(); } I have a class called Bar that can save and load lists of objects of type B: class Bar { void Save(List<B> ComplexItems); List<B> Load(); } B is a child of A. Foo, Bar, A and B are in a library and the user can create children of any of the classes. What I would like to do is something like the following: Foo MyFoo = new Foo(); Bar MyBar = new Bar(); MyFoo.Items = MyBar.Load(); MyBar.Save(MyFoo.Items); Obviously this won't work. Is there a clever way to do this that avoids creating intermediate lists? thanks, Andy

    Read the article

  • Getting the type of a parametrized class parameter?

    - by GuidoMB
    I have the following class public class MyClass<T> { public Class<T> getDomainClass() { GET THE CLASS OF T } } I've googled this problem and all the answers I could find told me to use getGenericSuperClass(), but the problem of this method is that I must have a second class that extends MyClass and I don't want to do this. What I need is to get the parametrized type of a concrete class?

    Read the article

  • Wouldn't it be nice to have a type variable referring to the class's instance.

    - by user93197
    I often have a pattern like this: class VectorBase<SubClass, Element> where SubClass : VectorBase<SubClass, Element>, new() where Element : Addable<Element> { Element[] data; public VectorBase(Element[] data) { this.data = data; } public SubClass add(SubClass second) { Element[] newData = new Element[data.Length]; for (int i = 0; i < newData.Length; i++) { newData[i] = data[i].add(second.data[i]); } SubClass result = new SubClass(); result.data = newData; return result; } } class VectorInt : VectorBase<VectorInt, Int32> { } class MyInt : Addable<MyInt> { int data; public MyInt(int data) { this.data = data; } public MyInt add(MyInt t) { return new MyInt(data + t.data); } } interface Addable<T> { T add(T t); } But I would rather just have: class VectorBase2<Element> where Element : Addable<Element> { Element[] data; public VectorBase(Element[] data) { this.data = data; } public SubClass add(SubClass second) { Element[] newData = new Element[data.Length]; for (int i = 0; i < newData.Length; i++) { newData[i] = data[i].add(second.data[i]); } SubClass result = new SubClass(data); return result; } } class VectorInt2 : VectorBase2<Int32> { } Why not make the subclass type available to all classes? Is this technically impossible?

    Read the article

  • implementing the generic interface

    - by user845405
    Could any one help me on implementing the generic interface for this class. I want to be able to use the below Cache class methods through an interface. Thank you for the help!. public class CacheStore { private Dictionary<string, object> _cache; private object _sync; public CacheStore() { _cache = new Dictionary<string, object>(); _sync = new object(); } public bool Exists<T>(string key) where T : class { Type type = typeof(T); lock (_sync) { return _cache.ContainsKey(type.Name + key); } } public bool Exists<T>() where T : class { Type type = typeof(T); lock (_sync) { return _cache.ContainsKey(type.Name); } } public T Get<T>(string key) where T : class { Type type = typeof(T); lock (_sync) { if (_cache.ContainsKey(key + type.Name) == false) throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key)); lock (_sync) { return (T)_cache[key + type.Name]; } } } public void Add<T>(string key, T value) { Type type = typeof(T); if (value.GetType() != type) throw new ApplicationException(String.Format("The type of value passed to cache {0} does not match the cache type {1} for key {2}", value.GetType().FullName, type.FullName, key)); lock (_sync) { if (_cache.ContainsKey(key + type.Name)) throw new ApplicationException(String.Format("An object with key '{0}' already exists", key)); lock (_sync) { _cache.Add(key + type.Name, value); } } } } Could any one help me on implementing the generic interface for this class. I want to be able to use the below Cache class methods through an interface.

    Read the article

  • When is a parameterized method call useful?

    - by johann-christoph-jacob
    A Java method call may be parameterized like in the following code: class Test { <T> void test() { } public static void main(String[] args) { new Test().<Object>test(); // ^^^^^^^^ } } I found out this is possible from the Eclipse Java Formatter settings dialog and wondered if there are any cases where this is useful or required.

    Read the article

  • C++ Generic List Assignment

    - by S73417H
    I've clearly been stuck in Java land for too long... Is it possible to do the C++ equivalent of the following Java code: // Method List<Bar> getBars() { return new LinkedList<Bar>(); } // Assignment statement. List<Foo> stuff = getBars(); Where Foo is a sub-class of Bar. So in C++.... std::list<Bar> & getBars() { std::list<Bar> bars; return bars; } std::list<Foo> stuff = getBars(); Hope that makes sense....

    Read the article

  • Interface with generic parameters- can't get it to compile

    - by user997112
    I have an interface like so: public interface MyInterface<E extends Something1> { public void meth1(MyClass1<E> x); } and I have a subclass whose superclass implements the above interface: public class MyClass2<E extends Something1> extends Superclass{ public MyClass2(){ } public void meth1(MyClass1 x) { // TODO Auto-generated method stub } } superclass: public abstract class Superclass<E extends Something1> implements MyInterface{ MyClass1<E> x; protected E y; public Superclass(){ } } the problem is that the parameter for meth1() is supposed to be generic. If I do MyClass1 it doesn't like it and the only way I can get it to compile is by leaving out generic parameters- which feels wrong. What's going wrong?

    Read the article

  • Getting the type of an array of T, without specifying T - Type.GetType("T[]")

    - by Merlyn Morgan-Graham
    I am trying to create a type that refers to an array of a generic type, without specifying the generic type. That is, I would like to do the equivalent of Type.GetType("T[]"). I already know how to do this with a non-array type. E.g. Type.GetType("System.Collections.Generic.IEnumerable`1") // or typeof(IEnumerable<>) Here's some sample code that reproduces the problem. using System; using System.Collections.Generic; public class Program { public static void SomeFunc<T>(IEnumerable<T> collection) { } public static void SomeArrayFunc<T>(T[] collection) { } static void Main(string[] args) { Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)"); Action<string> printFirstParameterType = methodName => printType( typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType ); printFirstParameterType("SomeFunc"); printFirstParameterType("SomeArrayFunc"); var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1"); printType(iEnumerableT); var iEnumerableTFromTypeof = typeof(IEnumerable<>); printType(iEnumerableTFromTypeof); var arrayOfT = Type.GetType("T[]"); printType(arrayOfT); // Prints "(null)" // ... not even sure where to start for typeof(T[]) } } The output is: System.Collections.Generic.IEnumerable`1[T] T[] System.Collections.Generic.IEnumerable`1[T] System.Collections.Generic.IEnumerable`1[T] (null) I'd like to correct that last "(null)". This will be used to get an overload of a function via reflections by specifying the method signature: var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT }); // ... call someMethod.MakeGenericMethod some time later I've already gotten my code mostly working by filtering the result of GetMethods(), so this is more of an exercise in knowledge and understanding.

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >