Menu
  • HOME
  • TAGS

How to write generic factory method in swift?

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 :...

Why doesn't type inference work in this case

java,generics,type-inference

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())); } } ...

How can I call this generic function?

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 type inference: reference is ambiguous in Java 8, but not Java 7

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...

Return types for unimplemented methods in traits

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...

Ocaml Type-inference of fun f [x; y; z] -> (f x y), (f z);;

ocaml,type-inference

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...

Implicit parameters break type inference or inference does not suffice for their resolution?

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...

Can I get Scala to infer the Option type here?

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...

Getting over type parameter bounds error with type checked by TypeTag

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 _ =>...

Accessing the generic parameter of generic parameter?

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...

F#: Function parameter defaults to obj in class

generics,f#,type-inference

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. ...

Why are type parameters are not allowed on this type?

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...

Swift parameter's type not properly inferred?

swift,type-inference

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...

Why is generic parameter not required to be set explicitly?

scala,type-inference

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...

How does c++ compiler infer template parameters when only some provided

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......

Type inference inconsistency between toList and toBuffer

scala,type-inference

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...

Inferred type in a Scala program

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:...

Generic artihmetical operations on generic types in F#

generics,f#,type-inference

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...

Why method of class does not have access to some field of my class?

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; }; ...

How can I get information about type of a Go variable

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....

How do I specify a type variable used in an inline type, is the same as a type variable used in a function definition?

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...

Generic method type inference when the target type has a wildcard

java,generics,type-inference

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...

OCaml: type inference with polymorphic variants

ocaml,type-inference

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...

How to get generic field type (string representation) with help reflection - Java?

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>>>>>> ...

Fixing type inference for higher kinded type

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]...

How does type inference work with overloaded generic methods

c#,generics,type-inference

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 type bounds not infered correctly in match statement

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](...

Inferring template parameters

c++,templates,type-inference

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 strange type inference narrowing [duplicate]

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...

Can function type be defined by inference?

function,scala,type-inference

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...

Generic methods type inference

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...

Calling non-strict function in Scala with explicit types doesn't compile, inferred types works

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...

Why compiler can't infer correct type in foreach of Regex.Matches?

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...

Typed integer constant in OCaml

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...

Why can't this method infer its parameter type from the Predicate parameter in the signature?

c#,generics,type-inference

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...

Why can't I remove the Ord Typeclass from this haskell implementation of Kadane's algorithm?

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...

In scala, why doesn't lower bound work well here?

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)...

How to change from which argument is the type inferred in generic methods?

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...

Why does this Java 8 program not compile?

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.

Scala unexpected type inference troubleshooting

scala,type-inference,scalac

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]{}...

Confusion over Java generic method type inference

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...

Is it possible to get the infinite kind error in Haskell 98?

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...

How to read data from Excel starting from given row and getting proper type inference

.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 type inference with lower bounded types

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...

F# Type inference with curried functions

types,f#,type-inference

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 does-not want to type high rank polymorphism

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...

Why isn't Scala picking the most specific instance in this this type class?

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....

Can java infer the generic type from a class defined on top of generics?

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...

C# Type Inference fails with methods that contain default parameters

c#,type-inference

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...

Generic F# operators fun

generics,f#,type-inference

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...

Type inference against type defined in unreferenced namespace

c#,namespaces,type-inference

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.

Make java compiler output type inference information

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 object initialization with diamond operator terrible javac compile time performance

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...

Why doesn't this Java 8 stream example compile?

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 can I get the Scala compiler to infer the type of this function?

scala,generics,type-inference

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...

Infinite loop seems to confuse Scala's type system

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....

Why does this list comprehension return an Array{Any,1} instead of an Array{Symbol,1}?

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....

In Scala, how to use `Nothing` as returned value to Fake a method?

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...

Type Inference in Haskell v. Scala

scala,haskell,type-inference

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...

type inference of (>>)(>>) (function composition)

f#,type-inference

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 =...

F# type inference less generic than indicated by the type annotations

generics,f#,type-inference

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 type inference for both a generic type and it's type parameter - why doesn't it work?

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...

Strange Swift numbers type casting

swift,casting,type-inference

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...

FSharp: Type inference with generic

generics,f#,type-inference

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...

Why can't I define the following CoFixpoint?

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 8 type inference static method call

java,generics,type-inference

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...

How to get better Polymorphic Type Inference in Haskell for this example?

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...

In Scala, why `_` can't be used in groupBy here?

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...

Implementing simple type inference

c,type-inference

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...

F# compiler inferring concrete types from first use of generic functions when currying

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...

Why Scala does not have a decltype?

scala,type-inference,decltype

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 ...

Is there such a thing as “public var Method()”?

c#,var,type-inference

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...

IEnumerable> and LINQ type inference

c#,linq,type-inference

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++ template parameter type inference

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...

Can I obtain an unwrapped singleton type in Scala with a simple method?

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 generic: how to declare a generic parameter as the base type of another generic parameter?

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(); ...

Can't infer type in generic tostring method C#

c#,types,type-inference

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...

Why is this type inference not working with this Lambda expression scenario?

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 deducing constraints works in cabal package, but not when importing from package

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...

Why doesn't overload resolution work here?

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...