generics,swift,factory,type-inference
Right now I don't have an answer about the why, but defining a protocol with the initializer only seems to work: protocol A { init(_ value: String) } You implement this protocol in all classes as below class Base : Printable, A { let value : String; init(_ value :...
It would be simpler to declare your class like this: public static class GenericSortingDTO<T extends Number> implements Comparator<GenericSortingDTO<T>> { //your current code here @Override public int compare(GenericSortingDTO<T> o1, GenericSortingDTO<T> o2) { return new BigDecimal(o1.getParameter().toString()).compareTo(new BigDecimal(o2.getParameter().toString())); } } ...
swift,generics,protocols,type-inference
@Roman Sausarnes' answer is correct, but instead of having the method instance, you could instead use an initialiser: protocol Prot { func doSomething() init() } class Classy: Prot { func doSomething() { println("Did something") } // The required keyword ensures every subclass also implements init() required init() {} } func...
java,generics,compiler-errors,java-8,type-inference
The problem is that the type inference has been improved. You have a method like public <T extends Base> T get() { return (T) new Derived(); } which basically says, “the caller can decide what subclass of Base I return”, which is obvious nonsense. Every compiler should give you an...
scala,types,casting,type-inference,traits
You can add a generic parameter: trait SomeTrait[T <: SomeTrait[T]] { def func(x: Int): T } class ExtensionClass(val param: String) extends SomeTrait[ExtensionClass] { def func(x: Int) = new ExtensionClass("test") def anotherMethod: String = param ++ "!" } alternatively you could add an abstract type member: trait SomeTrait { type T...
Okay, let's evaluate type of fun f [x; y; z] -> (f x y), (f z) this. Our function takes to arguments and returns a tuple. So it's type will be _ -> _ -> _ * _ where underscores are not evaluated yet parts. We will evaluate them below...
scala,type-inference,typeclass,implicits
The issue here is that scala cannot infer the O type because it is not present in Insert // I is in the parameter list but there is no O to be found case class Insert[I, O](arg: I)(implicit evidence: Ordering[O]) This leaves the compiler no choice but to infer O...
scala,coding-style,type-inference
When you use Option(Map.empty[A, B]) as the start value of your foldLeft, Scala will infer the correct type as I wrote in the comments (and beefyhalo in his answer). I would like to add, that if you are open to using Scalaz, you can just use the sequence function. import...
scala,reflection,type-inference,type-erasure
Is that what you want: object NotAnyMoreMysteryD extends App { def stupiderFunc[A: TypeTag, Z: TypeTag, T[_]](arg: List[A])(implicit ev: A =:= T[Z]) = typeOf[A] match { case t if t <:< typeOf[List[_]] => println("its a list of list of string") case t if t <:< typeOf[Set[_]] => specialFunc(arg.asInstanceOf[List[Set[Z]]]) case _ =>...
c#,generics,type-inference,generic-variance
C# doesn't support type inference on constructors, but what you can do is delegate calls to the constructors through a static method: public static class MiddleConsumer { public static MiddleConsumer<T> Create<T>( IConsumer<T> consumer ) where T : class, IBase { return new MiddleConsumer<T>( consumer ); } } Now you shouldn't...
Your first x.Func is defining a property, not a method and because properties cannot be generic it has to use a concrete type for 'a. When you define x.Func y you are creating a method and that can be generic. ...
generics,macros,rust,type-inference
this is actually an inconsistency with enums that was discussed but not considered important enough to block 1.0. The working syntax to specify types is Result::Ok::<i32, u32>(3). An enum works like something between a type (that would go with the syntax you were trying to write) and a namespace (and...
Well the problem here (as @Thilo already mentioned) is the ambiguity of protocol conformance. Character > ExtendedGraphemeClusterLiteralConvertible > UnicodeScalarLiteralConvertible UnicodeScalar > UnicodeScalarLiteralConvertible The compiler checks these protocols, but when it hits UnicodeScalarLiteralConvertible it has no idea which initializer to choose. You could make this easier by extending String with a...
Underlying Config object 'underlying: Config' has method getInt with return type Int, and this information provides enough evidence to infer type parameter for readValue, so you don't need to define it explicitly http://en.wikipedia.org/wiki/Type_inference http://docs.scala-lang.org/tutorials/tour/local-type-inference.html - example with id function should be helpful...
c++,templates,c++11,type-inference
I was just wondering how the compiler knows that TEq01 is class Q instead of class V? I'm using visual studio 2013. The first template argument you provide is the first template parameter. The order of template parameters is maintained. Since you wrote: template<class Q, class V> bool EQ......
Look at the definitions of toBuffer and toList: def toBuffer[A1 >: A]: Buffer[A1] def toList: List[A] As you can see, toBuffer is generic, while toList is not. The reason for this difference is - I believe - that Buffer is invariant, while List is covariant. Let's say that we have...
scala,type-inference,read-eval-print-loop
Perhaps TypeTag is what you are looking for? scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> def typeOf[T](x:T)( implicit tag: TypeTag[T] ) = tag typeOf: [T](x: T)(implicit tag: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T] scala> class Foo( a:Int ) defined class Foo scala> trait Bar defined trait Bar scala> val x = new Foo(3) with Bar x:...
It says requires / twice because the types are not necessary the same, so your function is going to be more generic than you expect. When designing generic math libraries some decisions must be taken. You can't just go ahead without type annotating everything or restricting math operators, type inference...
c++,templates,c++11,smart-pointers,type-inference
When T and U are different types, then linked_ptr<T> and linked_ptr<U> are different types. This means they can not see the private members of the other. You need to make other linked_ptrs friends: template <class T> class linked_ptr { // The rest... template<class U> friend class linked_ptr; }; ...
variables,types,go,type-inference
You are looking for something like godef If the -t flag is given, the type of the expression will also be printed. The -a flag causes all the public members (fields and methods) of the expression, and their location, to be printed also; the -A flag prints private members too....
haskell,type-inference,type-variables
You need to enable the ScopedTypeVariables extension, and the change the type signature of the top-level function to start with forall a .: {-# LANGUAGE ScopedTypeVariables #-} ... tryMaybe :: forall a . IO a -> IO (Maybe a) ... The forall syntax brings the type variable a into scope...
Each usage of a wildcard has a distinct type associated with it. (Usually the JLS refers to this as being a "fresh type".) This is how for example a compiler error like this works: List<?> list0 = ... ; List<?> list1 = ... ; list0.add(list1.get(0)); // error Because it's the...
This is yet another instantiation of the let-polymorphism constraints, that hinders the usage of polymorphic recursive function. Since, OCaml 3.12 we have an explicit way to declare that your function is polymorphic. Your case is a little bit more complex, since you have implicit type variable, that occurs inside the...
java,reflection,types,type-inference
Try this: for (Field field : Class1.class.getDeclaredFields()) System.out.println(field.getGenericType()); Output: java.util.Map<java.lang.String, java.lang.Integer> int class [I java.util.List<java.util.ArrayList<java.lang.String>> java.util.ArrayList<java.lang.String>[] java.util.List<java.util.List<java.util.List<java.util.ArrayList<java.util.List<java.util.List<java.lang.String>>>>>> ...
scala,type-inference,higher-kinded-types
The following "redundancy" seems to satisfy the compiler: def apply[S <: Sys[S], E1 <: Elem[S]](elem: E1 with Elem[S]): AttrElem[S] { type E = E1 } = ... That is, adding with Elem[S]. It looks like a needless deficiency of the Scala compiler to not infer S from E1 <: Elem[S]...
Assuming your Add methods are in the class named DataCollector; you can add extension method which accepts InfoData<ExtraInfo> and returns the same type as shown below. public static class DataCollectorExtensions { public static InfoData<ExtraInfo> AddInfoData(this DataCollector dataCollector, InfoData<ExtraInfo> data) { return dataCollector.Add<InfoData<ExtraInfo>, ExtraInfo>(data); } } In this way you have...
scala,pattern-matching,type-inference,typeclass
There are two issues getting in the way, one with the scoping of view and context bounds, the other with type erasure. 1. Scoping These: case class GreaterThan[T <% Ordered[T]]( a:Expr[T], b:Expr[T]) extends Expr[Boolean] case class GreaterThan[T : Ordering]( a:Expr[T], b:Expr[T]) extends Expr[Boolean] Are syntactic sugar for: case class GreaterThan[T](...
In this: template<typename T, size_t N, typename KT, typename VT> VT* Find(T<KT,VT> (&A)[N], KT key) you are trying to use T as a template template parameter. The syntax is: template<template <class, class> class T, size_t N, typename KT, typename VT> VT* Find(T<KT,VT> (&A)[N], KT key) ...
haskell,ghc,type-inference,ghci
This looks like the effect of Monomorphism Restriction (introduced because otherwise there were incoherent things in the language, and the language designers couldn't come up with something less ugly): if something looks like a value rather than like a function (with arguments), it can't be polymorphic. (Your fstGt0 has no...
I'm not quite sure what you're trying to achieve here, if I understand correctly you want to avoid typing (a:Int, b:Int, x:Double, y:Double, name:String) two times. What about defining FType yourself upfront and then simply reusing it in f and callF? object Foo { type FType = (Int,Int,Double,Double,String) => Unit...
delphi,generics,type-inference
The reason it cannot infer T from a TProc<T>argument is that at that time TProc<TButton> is a constructed type without any information that it originally was a TProc<T>. To do that it would have to infer the type from the anonymous method signature which does not work (I guess Barry...
scala,types,lazy-evaluation,type-inference
Yes, by-name ends up being part of the signature. You can imagine that by-name parameters are implemented by the compiler by translating this: def foo(n: => Int) = ... n ... to this: def foo(n: () => Int) = ... n() ... A side effect of this is that, if...
c#,compiler-errors,type-inference
But, shouldn't the compiler infer that chap is of type Match instead of object? Matches returns a MatchCollection which is not generic, it's enumerator method returns an object. So there is no way for the compiler to infer the type.It works when you use Match because underlying items are...
type-conversion,ocaml,type-inference
Use do_something_with_foo 99L. The constant 99 has type int, 99L has type int64. This has nothing to do with the type alias foo_t = int64. As long as the definition of foo_t is visible (i.e. not masked by the signature of a containing module), any value of type int64 also...
C# compiler is not allowed to use the return value of a method to resolve the method itself, including any type inference. Neither the method group string.IsNullOrEmpty nor the lambda i => i == 0 provide sufficient information to derive T in the ValueOrDefault<T> call. The compiler cannot use the...
algorithm,haskell,types,type-inference,type-systems
You cannot remove Ord since you are using functions like < and > and operating them on polymorphic type. See their type: λ> :t (<) (<) :: Ord a => a -> a -> Bool But if you instead limit your polymorphic code to operate only on Int or any...
scala,generics,types,functional-programming,type-inference
After reading the document about bounds, I found the correct way is to write like this: def insert_orderedCodeTreeList[T <: CodeTree](leaf: T, orderedCodeTrees: List[T]): List[T] = orderedCodeTrees match { case Nil => List(leaf) case head :: tail => { if (weight(leaf) <= weight(head)) leaf :: orderedCodeTrees else head :: insert_orderedCodeTreeList(leaf, tail)...
c#,generics,lambda,type-inference,linq-expressions
No, you can't affect type inference that way - and if it did infer TVal as short, your code wouldn't compile, because there's no implicit conversion from int to short. Surely the best solution is just to avoid using two different types to start with: short code = 404; Utils.SetPropertyValue(m...
java,generics,type-inference,java-8
Thanks for the report. This looks like a bug. I will take care of it and probably add a better answer once we have more information about why this is happening. I have filed this bug entry JDK-8043926, to track it.
Ok, I tried to put together a simple example and it compiles just fine on my machine, using sbt 0.13.7 on scala 2.11.4 package example object Main extends App { trait Request[I,+O,C[_]] trait W[A] trait R[A] trait ValidKey[A] implicit val wString = new W[String]{} implicit val rInt = new R[Int]{}...
java,wildcard,type-inference,generic-type-argument
This call does not bind T to a specific class. Java does not need to know the exact T because of type erasure implementation of the generics. As long as the types that you pass are consistent with the declaration, the code should compile; in your case, lists of Object...
haskell,functional-programming,ocaml,type-inference,unification
data F f = F (f F) On GHC 7.10.1, I get the message: kind.hs:1:17: Kind occurs check The first argument of ‘f’ should have kind ‘k0’, but ‘F’ has kind ‘(k0 -> k1) -> *’ In the type ‘f F’ In the definition of data constructor ‘F’ In the...
.net,excel,datatable,ado,type-inference
This is a dark road you have started down. I've been down it recently and after trying several options, I ended up going with ExcelDataReader. This is a nice .NET library that does a decent job importing data from .xls and .xlsx files. Basic importing is below: IExcelDataReader excelReader =...
java,generics,type-inference,bounded-wildcard
I think I can explain why Java differentiates between a lower-bounded and upper-bounded type. Trying to infer a common lower bound can fail when incompatible bounds are used, for example Integer and Long. When we're using an upper bound, it's always possible to find some common upper bound, in this...
What you are facing here is an aspect of F# called value restriction. This essentially means that if you define a value that is not syntactically a function, then it cannot be generic. let bar foo baz = foo, baz ... is syntactically a function (it obviously has two arguments)...
haskell,polymorphism,type-inference,system-f
Inference with RankNTypes is tricky. Try annotating the function instead of the argument. c :: Test Identity c = (cons :: Identity -> Test Identity) t Why this is so requires delving into the intricacies of the type inference algorithm. Here's some intuition behind that. Intuitively, whenever a polymorphic value...
scala,type-inference,typeclass
I'm not sure I fully understand your question. As far as choosing fooAny vs fooKV, the instance of Foo must be known and passed appropriately from the site where the types are known. This would be the place where mymap is called. Foo is not passed as a parameter though....
java,generics,type-inference,nested-generics
No. In the ConverterUser class definition, the TFrom and TTo type parameters have be to introduced somewhere, so that they are used in the TConverter extends IConverter<TFrom, TTo> type definition. This is why the ConverterUser results with three type parameters. Note that you can still get rid of the second...
There are two overloads for Select(). One that takes as the second parameter (i.e. the delegate) a Func<TSource, TResult>, and one that takes a Func<TSource, int, TResult>. I.e. a method signature with either one parameter or two. Your method satisfies neither. Even with the default values, it still has three...
As explained in the other answer the problem is tupled vs. curried arguments, by defining your function like this will solve the main issue: let inline (=~) x y = AlmostEqual $ (x, y) Anyway I would advise you to change your members definition as well, because you may have...
The reason for var foo = new FooFactory().GetFoo(); compile is simple. The compiler infer that foo is Models.Foo type not only Foo. Is symilar to push Models.Foo foo2 = new FooFactory().GetFoo();. Notice that Foo foo2 = new FooFactory().GetFoo(); is diferent.
java,generics,javac,type-inference
It's possible to see with a lot of detail what javac has inferred / resolved etc. To do that you need to use the hidden / unsupported / undocumented option: -XDverboseResolution. If one want to see all the information then the value to pass is 'all' as in: -XDverboseResolution=all. If...
java,collections,type-inference,diamond-operator
I'm currently working on JEP-215 Tiered attribution. The goal of this JEP is to improve the attribution code in javac, and as a side effect to improve the compiler's performance. For example the code listed in bug JDK-8055984 is compiled by "normal" Javac9 in: a lot of time! The current...
java,java-8,type-inference,java-stream
As Peter Lawrey pointed out, ? extends Example<?> is not compatible with E extends Example<E>. Still, even fixing the signature doesn’t make type inference work here. The reason is a known limitation of the type inference as it does not back-propagate through chained method invocations. In other words, the return...
How about just: def mapObjects[T](lst: GenSeq[HasGetter[T]]): GenSeq[T] = { lst map {v => v.getT} } scala> mapObjects(objs) res18: scala.collection.GenSeq[String] = List(abc, def, hij) There is no real advantage of using S <: HasGetter[T] in your case as you are just doing a map over lst and obtaining elements of type...
scala,infinite-loop,type-inference,return-type
You can also do: def foo: Int = { ... while(true) { ... return ... } throw new IllegalStateException // unreachable } this will typecheck because the type of the throw is Nothing, which is a subtype of Int....
arrays,type-inference,julia-lang
According to this discussion in the issue tracker of the JuliaLang/julia repo on GitHub, the problem seems to stem from a deficiency of Julia's type-inference system. Jeff Bezanson (one of the Julia writers and maintainers) left a relevant comment in another discussion: This behavior is actually expected at the moment....
scala,testing,functional-programming,mocking,type-inference
Since you need to return something of type Future[UserProfile], you'll just need to make up a fake UserProfile and return it. So if UserProfile is defined like this: class UserProfile(id: Int, name: String) then do something like: def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = { // To be done Future(new...
You can add an instance for Num [Char] in Haskell, if that's what you want: {-# LANGUAGE FlexibleInstances #-} import Data.Function (on) import Data.Composition ((.:)) -- cabal install composition helper :: (Integer -> Integer -> Integer) -> (String -> String -> String) helper op = show .: on op read...
There have been several explanations of value restriction around here in the past; here is one I wrote that explains why it is necessary. For completeness I'll copy here the example code that would be incorrect if the value restriction was removed: let f : 'a -> 'a option =...
The generic type SomeClass is using a generic argument 'b in its constructor that is missing in its definition. Changing the type definition to type SomeClass<'a, 'b when 'a:equality> ... and the line with the warning to SomeClass(func, this) removes the error, and the returned class is of type SomeClass<'c,...
scala,generics,type-inference,type-parameter,higher-kinded-types
If you make A take a type paramater A[_] I think you can get the Scala compiler to agree with you instead of just making everything Nothing: def f[A[_] <: G[_], X <: Int](g: A[X]) As a side note, I usually take a look in the scalaz source whenever I...
Yes, I also found this quite surprising. Double conforms to both FloatLiteralConvertible and IntegerLiteralConvertible. Therefore a Double can be initialized with floating point literal let a = 3.0 or with an integer literal: let b : Double = 10 Now it might be unexpected for all of us with an...
here is a quick F#-interactive session on what I meant with cheat by using an interface (it just have to be some sort of member - so it can be a method on a class too of course): > type IParam = abstract getParam : string -> 'a;; type IParam...
ocaml,type-inference,coq,induction,coinduction
You need to declare A as implicit to ask Coq to infer it for you. There are a few ways of doing it: Add the following declaration to your file: Set Implicit Arguments.. This will cause Coq to turn on automatic inference for arguments such as A for Cons, allowing...
Java objects are created by means of the Constructor. Because this is the normal behavior, Java developers created the empty diamon as a sugar syntax feature. A static method for object instanciation is not supposed to occur as frequent as the constructor. They are used for a lot of other...
haskell,polymorphism,type-inference
Expanding @AndrewC's comment here. For making loadVal 3 work, do the type conversion while instantiating: instance PValues Integer where loadVal v = IV (fromInteger v) Now, if you want to make it work with Text type and don't want your user to explicitly annotate it, give both the instances for...
scala,functional-programming,type-inference
x.groupBy(_), like any method x.foo(_), means "turn this method into a function", i.e. y => x.groupBy(y). Because _ is used for many things, it also can mean "plug in the value here". However, the "plug in identity" doesn't work because of the meaning above. You can do x => x...
My current idea was to just use the first type as the inferred type No. Usually, the expression's type is that of its "widest" term. If it contains a double, then it's a double. If not but contains a float, then it's a float. If it has only integers then...
generics,f#,type-inference,currying
Automatic generalization doesn't apply to value bindings in the way it applies to function bindings. This means that it can cause problems if the binding isn't syntactically a function, i.e. doesn't have arguments. Try this: let groupOp a = requestToGroup services a (In cases with static resolution, inline can be...
My first stab: class Decl[T] { type Type = T } object Decl { def apply[T](x: T) = new Decl[T] } For example, if we have some variable x whose type we don't want to state explicitly: val d = Decl(x) type TypeOfX = d.Type ...
No, there isn't. Per the specification, using the identifier var for implicit typing is only allowed in the context of a local variable declaration. Eric Lippert's article on why var is not valid for fields raises a number of issues with implementing it outside the local variable context, which apply...
All the information about the type isn't known beforehand. In your first working snippet, you're telling it on both lines which delegate type you want s => s.Substring(n) to be converted to. In your second snippet, the only place where that information is present is in the assignment of the...
c++,templates,type-inference,inferred-type
Since you are asking about a pure class template-based solution without the help of macro definitions then the answer is simple: as for now (Dec 2014, C++14) it is not possible. This issue has been already identified by the WG21 C++ Standard Committee as a need and there are several...
scala,type-inference,shapeless,singleton-type
This is a known quirk of scalac. Singleton types are a compiler internal and they've been there for a long time, but they've never been meant to be exposed to the users. So, there's no guarantee about their "API" and as a matter of fact scalac tries to make them...
java,generics,types,type-inference
how can I make sure that java infers twoCars.replaceFirst(new Tank()) to return a Pair of Vehicle instead of a Pair of tanks? Provide a type argument explicitly twoCars.<Vehicle>replaceFirst(new Tank()) You'll get a compiler error when trying to invoke Tank actuallyACar = twoCars.<Vehicle>replaceFirst(new Tank()).second(); ...
You do not need to use generics here, you can define GetString with the non-generic collection interfaces and the compiler will bind your calls to the most specific one. For example: public static String GetString(object value) { if (value is string) { return value as string; } else if (value...
java,lambda,java-8,type-inference
Under the Hood Using some hidden javac features, we can get more information about what's happening: $ javac -XDverboseResolution=deferred-inference,success,applicable LambdaInference.java LambdaInference.java:16: Note: resolving method foo in type Foo to candidate 0 Foo.foo(value -> true).booleanValue(); // Compile error here ^ phase: BASIC with actuals: <none> with type-args: no arguments candidates: #0...
haskell,cabal,type-inference,state-monad
I ended up just making a file at Game/Monad.hs containing: module Game.Monad (execStateT, MonadState, MonadIO) where import Control.Monad.State Then replaced my import Control.State.Monad with import Game.Monad in GreedyInference.hs. The file then compiled without the error. So I think @Rufflewind in the comments was on the right track - the mtl...
c#,generics,covariance,type-inference,method-overloading
Your Foreach method will be inferred as Foreach(Action<byte> action). There is no WriteLine overload which takes a single parameter byte and thus it doesn't compile. What's up with that? Why can't it compile with Console.WriteLine(int)? Because Action<int> isn't compatible to Action<byte> From C# language specification 15.2 Delegate compatibility: A method...