w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I get type parameter from type with type parameter, inside scala macro?
You can use the TypeRef extractor: import reflect.runtime.universe._ // or in a macro "c.universe._" val tpe = weakTypeOf[List[Int]] // extract type parameters val TypeRef(_,_, tps) = tpe // tps has type List[Type] println(tps.head) // Int

Categories : Scala

A subclass type as parameter type in superclass constructor java
Use Inheritance public interface Node{ //... } public class SimpleNode implements Node{ //... } public class ComplexNode implements Node{ //... } Then, you can add a Constructor like that: public class SimpleNode implements Node{ public SimpleNode(int numberOfNode){ //... } }

Categories : Java

How do I make an instance of generic subclass? Getting error: "Bound mismatch: The type ... is not a valid substitute for the bounded parameter ..."
In your code, Team is just a placeholder (in this context, called Type Variable) and happens to be hiding the type Team, not referencing it. In other words, that declaration is equivalent to: public class ChampionsLeague<T extends Comparable<T>> extends League<T> { So it is really only asking for a class (or interface) that implements (extends) Comparable of itself. So this example: public class Ball implements Comparable<Ball> { @Override public int compareTo(Ball o) { return 0; } } // or: public interface Ball extends Comparable<Ball> { } Will work: ChampionsLeague<Ball> test = new ChampionsLeague<Ball>(); Edit: Some possibilities to what you may be trying to achieve: // ChampionsLeague needs a type Comparable to Team public c

Categories : Java

JSF: auto conversion when backing a view item with an instance of a subclass of a generic class with resolved type parameter
I've done something similar a couple months ago addressing a different problem. I have an abstract class for many of my JPA entity classes. Every entity converter of that type had almost the same logic and I wanted to use a single converter for that. After a little research I was able to find a solution for an abstract converter for my entities where I could place the common logic. The only problem is that now I need to reference-it by its name (converter="entity"). This solution was found somewhere else (I can't remember where) so I can't take any credits here. The abstract converter: import java.util.HashMap; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; public abstract class AbstractCo

Categories : Java

Refer generic without type parameter in Scala
I believe I can achieve your aim, but using type members rather than type parameters. Also, this meant I could move the implementation of addChild into the trait and not re-implement it in the subclasses. Finally, I added a marker trait, IntervalMarker, to label the two node types that EndNode can accept as children. trait TreeNode { type ChildType <: NonRootNode val children:HashSet[ChildType] = new HashSet[ChildType] def addChild(c:ChildType) = { children.add(c) } } abstract class NonRootNode extends TreeNode { var passengers:Set[Passenger] = Set() } case object RootNode extends TreeNode { type ChildType = TimeNode } trait IntervalMarker case class TimeNode(time:Int) extends NonRootNode with IntervalMarker { type ChildType = StartNode } case class StartNode(l:Opt

Categories : Scala

Why this Scala code hangs if you specify type-parameter?
I'm not sure what you're trying to achieve here. I don't really have any experience with type-level programming in Scala, but this doesn't look like correct type-level programming to me. What exactly are you trying to achieve with the type parameter Y in xToNextPage[Y](x : X)? The only possible value for Next[X, Y] is Next[X, AnyRef], since the least-common-ancestor of Foo and Bar is AnyRef. Getting rid of the Y gives you the only correct answer: trait NextPage[Curr, Next] { def next : Next } class Foo class Bar class X(val year : Int) object X { implicit def xToNextPage(x : X) = if (x.year == 2010) { new X(x.year) with NextPage[X, Bar] { def next = new Bar } } else { new X(x.year) with NextPage[X, Foo] { def next = new Foo }

Categories : Scala

How to get a type in Scala AST of underscored lambda function parameter?
Number ~> ((_:Int) + _) is transformed to something like this pimpActionOp[...](rule).~>.apply[...](function) type classes of pimpActionOp and apply contain all necessary information to restore types.

Categories : Scala

Scala classOf on class with recursive type parameter
How about simply classOf[Order[_]]? (BTW, your Java declarations are using raw types — most likely, you'll need to declare things like class Order<O extends Order<O, I>, I extends Item<O, I>> and class Item<O extends Order<O, I>, I extends Item<O, I>>.)

Categories : Java

Scala Macros, generating type parameter calls
This will probably not fill all your needs here, but it may help a bit: The signature of table method looks like this: protected def table[T]()(implicit manifestT: Manifest[T]): Table[T] As you can see, it takes implicit Manifest object. That object is passed automatically by the compiler and contains information about type T. This is actually what Squeryl uses to inspect database entity type. You can just pass these manifests explicitly like this: val listOfManifests = List(manifest[Person], manifest[Bookmark]) listOfManifests.foreach(manifest => { val tbl = table()(manifest) tbl.id is indexed etc. }) Unfortunately tbl in this code will have type similar to Table[_ <: CommonSupertypeOfAllGivenEntities] which means that all operations on it must be agnostic of concrete

Categories : Scala

Scala: Declaring method with generic type parameter
I. Very close to what you want: def readValue[T:ClassTag](s:String):T = { val tClass = implicitly[ClassTag[T]].runtimeClass //implementation for different classes. } usage is a bit clearer than in Java: val myDouble = readValue[Double]("1.0")

Categories : Scala

Scala error implementing abstract method with type parameter
You may want to define a type T to do away with Trait Type Parameters and accomplish the same as.. trait T1 { type T def f1(a: T): Double } val ea1 = new T1 { type T = List[String] def f1(a: T): Double = a.length } ea1.f1(List("1","2")) // res0: Double = 2.0

Categories : Scala

Scala Tuple not show type mismatch if passing parameter inline
The problem is due to your code depending on implicit conversion in which case it does not happen when you pass the testTuple inline. If you use val x:Double = 2 it should work.

Categories : Scala

Why there is a ClassCastException when isInstanceOf returns true on a scala type with wildcard parameter?
TypeRef is an abstract type, therefore it's erased to its upper bound. Typically this means that it's impossible to do reliable isInstanceOf and pattern matching (which ultimately relies on that). However since reflection API extensively uses abstract types, we built in a special mechanism to pattern match instances of abstract types, based on class tags. If in scope you have a class tag corresponding to the abstract type, everything works reliably. Naturally, we provide a bunch of class tags bundled in universes, one per almost every abstract type. The catch is that you do need to import those class tags. Usually that's not a problem, because almost everyone does import ru._, but in cases like that it comes up. We recognize this as an issue, but it remains to be fixed.

Categories : Scala

How to change subclass referenced by parent class to have a reference type of subclass?
Is there any way to change the type of eventDto in ProcessMessage() from EventDto to its actual derived type (say, of EventDtoSubclass2)? No. You either know the type ahead of time (and can either cast it or use it as a generic type parameter or whatever) or you have to detect it after the fact and branch on it. Since it appears you don't know ahead of time what you're getting, then you need to detect it and branch on it (and by that I mean using is/as or GetType/typeof or whatever your favorite method of checking is). As somewhat of an alternative, if you can change your EventDto-derived classes, you could potentially add a virtual Process function to the base class with overriden versions in each derived class that do the right thing. That depends on what Process actually does, tho

Categories : C#

create type from pattern matching in scala
I fear this is not possible, for fundamental conceptual reasons. As type rules are checked at compile time, it is not possible to derive types based on values that might be unknown until runtime. That being said, you might be able to tackle your design problem by defining a family of case classes, each being a wrapper for a value of a specific type. By giving these classes a common base class, you can store a value of any type you wish into the same variable and extract it through type-safe pattern matching: class Base case class AString(val value: String) extends Base case class AnInt(val value: Int) extends Base case class ADouble(val value: Double) extends Base val a : Base = "value1" match { case "value0" => AString(…) case "value1" => AnInt(…) case "value0" => AD

Categories : Scala

How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name
Whether this is indeed a design flaw is rather debatable. One would consider that complicating the syntax to allow this particular use case is not worthwhile. Also, Scala is after all a predominantly functional language, so the presence of vars in your program should not be that frequent, again raising the question if this particular use case needs to be handled in a special way. However, it seems that a simple solution to your problem would be to use an apply method in the companion object: class Foo private(private var _x: Int) { def x = _x } object Foo { def apply(x: Int): Foo = new Foo(x) } Usage: val f = Foo(x = 3) println(f.x) LATER EDIT: Here is a solution similar to what you originally requested, but that changes the naming a bit: class Foo(initialX: Int) { private

Categories : Scala

How to create an object attribute from polymorphic type in scala
Your problem is in that you are returning loaded(className) which is of type Bar, not T as is required by your function type signature. Unfortunately, you cannot encode such dependence between types of map keys and values, at least not with the standard map collection. You have to perform explicit cast. Here is a working example: import scala.reflect.ClassTag class Bar class FooBar extends Bar object Test { val classMap = scala.collection.mutable.Map[Class[_], Bar]() def getInstance[T <: Bar : ClassTag]: T = { val ct = implicitly[ClassTag[T]] classMap get ct.runtimeClass match { case Some(bar) => bar.asInstanceOf[T] case None => val instance = ct.runtimeClass.newInstance().asInstanceOf[T] classMap(ct.runtimeClass) = instance ins

Categories : Scala

How to use a generic type parameter as type parameter for a property declared as an interface with type constraints?
Try to add class constraint to the TItem: namespace Sample2 { public interface IInterfaceContainer<T1, T2> where T1 : T2 { } public interface IInterfaceParent { } public interface IInterfaceChild : IInterfaceParent { } public class ClassSampleDoesNotWork<TItem> where TItem : class, IInterfaceParent { IInterfaceContainer<IEnumerable<TItem>, IEnumerable<IInterfaceParent>> SomeProperty { get; set; } } } This works because variance only works for reference-types (or there is an identity conversion). It isn't known that TItem is reference type, unless you add : class. Read this article for more information. Here is a sample code to demonstrate this behavior: IEnumerable<Object> ite

Categories : C#

Can I create a member variable that is a type parameter of a generic?
This is the code corresponding to my first comment. As i said this involves unchecked casts. public static class MyProxy<S extends Service, P extends BindingProvider> { private static final MyProxy<? extends Service, ? extends BindingProvider> instance = new Proxy<Service, BindingProvider>(); private S service; public static <S extends Service, P extends BindingProvider> MyProxy<S, P> getInstance() { return (MyProxy<S, P>) instance; } }

Categories : Java

Create a Service instance with reference type parameter?
I would like to pass a List to this service to save locations You can use putStringArrayListExtra() to put an ArrayList<String> as an extra on an Intent.

Categories : Android

How to create a new object from type parameter in generic class in typescript?
Because the compiled JavaScript has all the type information erased, you can't use T to new up an object. You can do this in a non-generic way by passing the type into the constructor. class TestOne { hi() { alert('Hi'); } } class TestTwo { constructor(private testType) { } getNew() { return new this.testType(); } } var test = new TestTwo(TestOne); var example = test.getNew(); example.hi(); You could extend this example using generics to tighten up the types: class TestBase { hi() { alert('Hi from base'); } } class TestSub extends TestBase { hi() { alert('Hi from sub'); } } class TestTwo<T extends TestBase> { constructor(private testType) { } getNew() : T { return new this.testType

Categories : Typescript

Passing a class with type parameter as type parameter for generic method in Java
This is actually possible in Java, using some "tricks". Don't succumb to pressure from the C# fanatics! (j/k) The "trick" is to create a class that extends a generic type, and access the value of the type parameter of the parent class through the Type returned by .getGenericSuperclass() or .getGenericInterfaces(). This is quite cumbersome. To simplify our lives, Google has already written most of the boring part of the code for us, and made it available through Guava. Check the TypeToken class, which does exactly what you want. For example: TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {}; Then you pass around a TypeToken<T> instead of a Class<T> and that's all. It provides you with methods to do reflection on the type repre

Categories : Java

scala: how to view subclass methods with a generic instantiation
So you want the generic class Data[DataScheme] or Data[IndexScheme] to have access to the methods of whichever type Data has been parameterised with. You've tried to do this several different ways, from the evidence in your code. To answer your last question - manifests can't help in this particular case and TypeTags are only part of the answer. If you really want to do this, you do it with mirrors. However, you will have to make some changes to your code. Scala only has instance methods; there are no such things as static methods in Scala. This means that you can only use reflection to invoke a method on an instance of a class, trait or object. Your traits are abstract and can't be instantiated. I can't really tell you how to clean up your code, because what you have pasted up her

Categories : Scala

Scala: subclass a Java class with multiple constructors?
Use default values, for example: class ParentError(i: Double = 0, msg: String = null, cause: Throwable = null) extends Exception(msg: String, cause: Throwable) { ⋮ }

Categories : Scala

Cant declare an instance with type parameter that is one layer off the constraint of the type parameter
Since TypedTableBase is generic, when you use it, you have to specify the actual datatype as in public class A<T> where T:DataTable { } public class B :TypedTableBase<DataRow> { } class MyClass { A<B> asdf = new A<B>(); }

Categories : C#

Find method parameter type or parameter generic type
Please try using below code, you have to compare type and Integer.class public static void main(String[] args) throws ClassNotFoundException { Class<?> clazz = Class.forName("Test"); Class<Integer> lookingForClass = Integer.class; Method[] method = clazz.getMethods(); for (int i = 0; i < method.length; i++) { Type[] types = method[i].getParameterTypes(); for (int j = 0; j < types.length; j++) { Type type = types[j]; Class<?> result = type.getClass(); if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] fieldArgTypes = pt.getActualTypeArgume

Categories : Java

Generic inference of type parameter with constraint to other type parameter
You can't infer just some type parameters within a method call. Generic type inference either infers all type parameters, or none. There's no way of inferring THost from the parameters (there could be multiple classes which derive from HostBase<Config>), which means you basically can't use type inference for that method. Looking at this specific example, I think you're going to find it tricky to use type inference at all, because of the way the relationships work.

Categories : C#

std::function parameter subclass
You might need std::bind, like in B b; method(std::bind(&B::testCallbackB, b));

Categories : C++

Determining if type is a subclass of a generic type
Something like this should work. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Check(new Foo()); Check(new Bar()); Console.ReadLine(); } static void Check<T>(T obj) { // "The type T cannot be used as type parameter..." if (IsDerivedOfGenericType(typeof(T), typeof(Entity<>))) { System.Console.WriteLine(string.Format("{0} is Entity<T>", typeof(T))); } } static bool IsDerivedOfGenericType(Type type, Type genericType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)

Categories : C#

How to return a subclass from __new__ parameter
The problem is that inside parent.__new__, you're calling child1(e), while calls child1.__new__, which finds the implementation in parent.__new__ and calls it with the same e, which calls child1(e), which… so you get infinite recursion. There are better ways to design this, but if you just want to fix your design, there are three options: If you define __new__ in all of your subclasses, it won't fall through the parent.__new__. You can do this in a single step by interposing an intermediate class between parent and childN, so you only need intermediate.__new__. Or use a mixin that they all inherit, or … Get rid of the inheritance. Is there really any reason child1 is-a parent here? You seem to be looking for what in Smalltalk/ObjC terms is called a "class cluster", and you don

Categories : Python

Scala type mismatch: default.type (with underlying type A1 => B1)
Strange, as soon as I renamed default variable, everything compiled fine: scala> def composeHandlingFuture[T](fut: Future[T], x: T): Future[T] = | fut recover { case e: Exception => x } composeHandlingFuture: [T](fut: scala.concurrent.Future[T], x: T)scala.concurrent.Future[T]

Categories : Scala

Can you pass a subclass as an argument to a function with a superclass parameter? C++
Array does not hold polimorphism, you could archive this by using vector of pointers and pass the reference to the vector into the function. Something like: #include <memory> #include <vector> void shift_shapes(std::vector<std::unique_ptr<Shape> >& shapes, int num_shapes, int x_offset, int y_offset) { for (int i = 0; i < num_shapes; i++) { shapes[i].move(x_offset, y_offset); } }

Categories : C++

A platform for Java, Scala, Groovy and jRuby would be implemented in what language?
I am by no means an expert and have never done such a cross-language project (just minor Java/Scala). But I would suggest implementing it in the language: you know best makes you most productive ensures the most maintainability In my case it would be Scala. So what I would do is define the API in the form of Java interfaces, which I would then implement in Scala (probably I would need to convert Scala/Java collections back-and-forth, but that would be an implementation detail). That way you make sure that other JVM languages can interact with your API, and you implement it in whatever language you are best.

Categories : Java

Scala: higher-kinded types, type projections and type mismatch error
@ziggystar says it: Drop the bound B and use M[X] directly: class TransM[X[_]](val b: M[X]) extends M[CurriedTrans[X, M[X]]#Type] { def from[A](f: T[A]) = b.from(f.r).get } val x1 = new TransM(new ListM) You could consider to do the same for Trans and CurriedTrans. If you need the inner type of M, you can always expose it through a type member of Trans and CurriedTrans.

Categories : Scala

scala type error for class with map member typed with existential type
Unless you explicitly require getting the keys back out as the statically correct subtype (which seems unlikely), then the following will work: case class DictVariant1(data: Map[MyBaseType, Double]) val d = List((Concrete1() : MyBaseType, 3.5)).toMap val dv1 = DictVariant1(d) Using a type ascription forces Concrete1() to be seen as an instance of the base type; you'd get the same effect if you added an explicit type to d: val d : Map[MyBaseType, Double] = .... Or if you put multiple entries in such that the type inferencer picks the base type: val d = List((Concrete1(), 3.5), (Concrete2(), 4.5)).toMap The 'get' you use is always going to fail, however, because you're trying to use the whole Map as an index: it works fine if you provide a sensible key: dv1.data.get(Concrete1())

Categories : Scala

Scala Type Mismatch underlying type and class vs method
The problem in your code is type parameter shadowing. You have: class ThreeStacks[A, B, C](val stackSize:Int = 1000) { def push1[A](value: A): Unit = stack1.push(value) ... } It should be: class ThreeStacks[A, B, C](val stackSize:Int = 1000) { def push1(value: A): Unit = stack1.push(value) ... } The way you have done it, type parameter A of class ThreeStacks and type parameter A of method push1 are completely different ones and thus, are incompatible with each other. The same applies to B and C.

Categories : Scala

Scala Structural type and existential type issue
I think it's an inference bug (or maybe a limitation) concerning the type construct. Edit: the error message was the first thing that made me think it was a bug: "type mismatch; found : Int(1) required: A" If you split the last line in to 2, i.e. val t3 = TMap(1,2) val t2: MapT2[Int] = t3 , then it produces a similarly pongy message: "type mismatch; found : Test1.this.TMap[Int,Int] required: Test1.this.MapT2[Int] (which expands to) Test1.this.TMap[A,A]" Given that A is a 'symbol' and Int is a class, it seems like it's comparing apples and oranges. Sorry I can't take this logic any further!

Categories : Scala

How to subclass QStandardItemModel to use my own Item type?
I think it is impossible. You can subclass QAbstractItemModel to implement a model that use your item class. Also you can use default QStandardItemModel and add your additional object to items using QStandardItem::setData. Since it accepts QVariant, you can put any value in it, event QSharedPointer (you need to register appropriate meta type).

Categories : C++

Determine Subclass Type of an Object of the Parent Class
What you seem to asking for is a factory pattern public interface ISign { public void operation1(); public void operation2(); } and a Factory class to generate classes based on input public class SignGenerator { public static ISign getSignObject(String str1,String str2, String str3, String str4) { if(str1.equals("blah blah")) return new FirstType(); if(str1.equals("blah blah2") && str2.equals("lorem ipsum")) return new SecondType(); return new ThirdType(); } } public class FirstType implements ISign { } public class SecondType implements ISign { } public class ThirdType implements ISign { } Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses fir

Categories : Java

To pass JSF expression language as parameter to javascript function
If you want to pass a variable from backing bean to a javascript method, Create a variable in beacking bean, say myVariable (add getter method) Add a4j:support to your button as follows, <h:commandButton action="#{workSpaceBean.submit}"......> <a4j:support event="click" onComplete="checkOption('#{workSpaceBean.myVariable}')" /> </h;commandButton>

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.