w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I parameterize filtering a collection of Scala objects by type?
In val f = Y Y is not a type, but companion object. You could use type like this: type T = Y l.collect{case e: T=>e} // returns List[Y] = List(Y(1), Y(2)) Or you could use companion object, but only for certain parameters count: val t = Y l.collect{case e @ t(_)=>e} // returns List[Y] = List(Y(1), Y(2)) In this case you should use e @ t(_, _) for case class Y(y1:Int, y2:Int), e @ t(_, _, _) for case class Y(y1:Int, y2:Int, y3:Int) and so on.

Categories : Scala

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest
You should add dependecy for scala-reflect to your maven build: <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-reflect</artifactId> <version>2.10.2</version> </dependency>

Categories : Scala

Convert scala.collection.immutable.Vector to java.util.Collection
You need to call asJavaCollection to do the conversion, this should work: import scala.collection.JavaConverters._ var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition()) request.setAttributeDefinitions(attrDefs.asJavaCollection) As an alternative, you can use import scala.collection.JavaConversions._ to not have to call asJavaCollection. However, I find that it makes what the code is doing more readable to call the method. Here's the alternate example: import scala.collection.JavaConversions._ var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition()) request.setAttributeDefinitions(attrDefs)

Categories : Java

Scala convert Iterable or collection.Seq to collection.immutable.Seq
Use the to method to convert between arbitrary collection types in Scala 2.10: scala> Array(1, 2, 3).toSeq res0: Seq[Int] = WrappedArray(1, 2, 3) scala> Array(1, 2, 3).to[collection.immutable.Seq] res1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)

Categories : Scala

Json Unmarshal reflect.Type
That doesn't make sense. There is no way for the JSON package to know what data should be decoded. This interface might be implemented by a struct{} type, an int type and maybe a struct{ Value1, Value2 int } type. Even worse, there might be other types as well, that are aren`t even part of your binary (missing imports, dead code elimination, etc.). So, which type do you expect to get back from JSON? You probably need to find another way. For example, you could implement the json.Unmarshaler interface, unmarshal an identifier and use that identifier to unmarshal the following data into a concrete type. The switch statement that you will probably need for that, will also ensure that the concrete type is part of your binary (since you are using it). But there is probably an easier solution.

Categories : Json

How to create Instance by java.lang.reflect.Type
(Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments ) The OP wrote: I just solved it with a stupid solution, its instantiation generics type by using Class.forName(); the class name came from type.toString() Type type = getGenericsType(method); Class<?> genericsType = null; try { genericsType = Class.forName(getClassName(type)); // now, i have a instance of generics type Object o = genericsType.newInstance(); } catch (Exception e) { } static String NAME_PREFIX = "class "; private static String getClassName(Type type) { String fullName = type.toString(); if (fullName.startsWith(NAME_PREFIX)) return fullName.substring(NAME_PREFIX.length()); return fullName

Categories : Java

Returning Collection vs Collection
Collection<Type> getTypes(); Here, getTypes() must return a Collection<Type> (e.g. ArrayList<Type> or HashSet<Type>). Collection<? extends Type> getTypes(); Here, getTypes() can return a Collection of anything that is or extends Type, (e.g. ArrayList<SubType> or HashSet<SubType>). So anything that can be returned from the first variant can also be returned from the second. In the second, however, you don't know what the type parameter of the collection actually is; you just know that it extends Type. As for which should be preferred, it really depends on what you're trying to do, and what makes more sense logically. Bear in mind that when you have <? extends Type>, you don't actually know what ? is, and this can be hindering at times; m

Categories : Java

Check if an object is a type of collection, regardless of what Type that collection is of?
You can do this by confirming that the type is a generic type, and its generic type definition is equal to the EntityCollection<> open generic type. var type = e.PropertyType; var isEntityCollection = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EntityCollection<>);

Categories : C#

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

Collection in Scala
Collection <?> args It's written Collection (pronounced "collection of unknown"), that is, a collection whose element type matches anything. It's called a wildcard type for obvious reasons. Read more about wildcards here For Scala Existential types and Usage of WildCards in Scala

Categories : Java

Scala Collection in JSF
This code is based on ScalaElResolver by Werner Punz. I have stripped it down, so it just handles the conversion from a Scala Iterable to a java.lang.Iterable: class SimpleScalaElResolver extends ELResolver { override def getValue(elContext: ELContext, base: AnyRef, prop: AnyRef): AnyRef = { println(s"SimpleElResolver: getValue: Entering: $base.$prop") if (base == null) { null } else { val method = base.getClass.getDeclaredMethod(prop.toString) if (method != null) { val res = method.invoke(base) if (res.isInstanceOf[Iterable[_]]) { val iter = res.asInstanceOf[Iterable[_]] println("getValue: Wrapping as Java iterable") elContext.setPropertyResolved(true) JavaConversions.asJavaI

Categories : Scala

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

populate HashMap programatically from collection in Scala
I don't know exactly what you want to do, but is it something like this? scala> val mergeMap = Map(("key1", "value1"), ("key2", "value2"), ("key3", "value1")) mergeMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(key1 -> value1, key2 -> value2, key3 -> value1) scala> mergeMap.values.toSet.map((_ : String, 1)).toMap res12: scala.collection.immutable.Map[String,Int] = Map(value1 -> 1, value2 -> 1) The first one makes a map from String to String (not from String to a Collection of Strings like in your example). The second one takes all the values from the map, and builds a new map with the values from the first map as keys and the default value 1 as each value. Duplicate keys are discarded (in the "toSet" step and would be

Categories : Scala

scala, filter a collection based on several conditions
You could easily use an implicit class to give you this syntax: val strs = List("hello", "andorra", "trab", "world") def f1(s: String) = !s.startsWith("a") def f2(s: String) = !s.endsWith("b") val cond1 = true val cond2 = true implicit class FilterHelper[A](l: List[A]) { def ifFilter(cond: Boolean, f: A => Boolean) = { if (cond) l.filter(f) else l } } strs .ifFilter(cond1, f1) .ifFilter(cond2, f2) res1: List[String] = List(hello, world) I would have used if as the method name but it's a reserved word.

Categories : Scala

Reading a collection of lists from file in scala
The simplest way is to use scala.io.Source to read the file line by line. With getLines, you can retrieve an Iterator[String] over which you can map to split the lines and convert them to ints like this: val intPairs = Source.fromFile("/path/to/file").getLines.map { line => line.split(" ").take(2).map(_.toInt) } I leave the grouping of consecutive lines as an exercise for you.

Categories : Scala

`::` head and tail deconstruction of a java collection in scala
Using your JavaCollection extractor, here is how you can sum the first two elements without knowing the actual length of the collection: scala> val m = Map("a" -> Seq(1,2,3,4,5).asJava, "b" -> Seq(1,2).asJava).asJava m: java.util.Map[java.lang.String,java.util.List[Int]] = {a=[1, 2, 3, 4, 5], b=[1, 2]} scala> m.asScala.collect { case (k, JavaCollection(a, b, rest @ _*)) => k -> (a + b) } res3: scala.collection.mutable.Map[java.lang.String,Int] = Map(a -> 3, b -> 3) scala>

Categories : Java

Scala: lazy evaluation on a Collection (Strategy Pattern)
I guess you mean Seq, not Map. You could use Seq instead of if sequence here, though I don't think its readable. You should use getOrElse after find. Assuming each lengthyOperationN is a function: seq.find(_._1).map{_._2}.getOrElse(lastLengthyOperation).apply()

Categories : Scala

Count occurrences of each item in a Scala parallel collection
If you want to make use of parallel collections and Scala standard tools, you could do it like that. Group your collection by the identity and then map it to (Value, Count): scala> val longList = List(1, 5, 2, 3, 7, 4, 2, 3, 7, 3, 2, 1, 7) longList: List[Int] = List(1, 5, 2, 3, 7, 4, 2, 3, 7, 3, 2, 1, 7) scala> longList.par.groupBy(x => x) res0: scala.collection.parallel.immutable.ParMap[Int,scala.collection.parallel.immutable.ParSeq[Int]] = ParMap(5 -> ParVector(5), 1 -> ParVector(1, 1), 2 -> ParVector(2, 2, 2), 7 -> ParVector(7, 7, 7), 3 -> ParVector(3, 3, 3), 4 -> ParVector(4)) scala> longList.pa

Categories : Scala

How to read Values from TYPE in Oracle for the Collection (Map) type
In SQL SELECT ivkey, ivvalue FROM TABLE( pValues ); would work. If you really mean to ask how to access the collection in PL/SQL, assuming the collection is dense. FOR i IN 1..pValues.count LOOP dbms_output.put_line( 'Key = ' || pValues(i).ivkey || ' Value = ' || pValues(i).ivvalue ); END LOOP; If you expect some elements of the collection to be missing (which seems odd given your choice of PL/SQL collection), the loop gets a bit more complicated since you've got to call FIRST and NEXT to iterate through the elements. If you want to create a PL/SQL construct that is more similar to your Map in Java, you'd want something like CREATE TYPE map_t AS TABLE OF VARCHAR2(250) INDEX BY VARCHAR2(32)

Categories : Java

Casting java.util.LinkedHashMap to scala.collection.mutable.Map
Importing the JavaConversions stuff doesn't make java's collection types instaces of the scala collection types, it provides handy conversion methods between the two distinct collection hierarchies. In this case, given the import in your question, you can get a mutable scala Map from your java LinkedHashMap with the line: val s = mapAsScalaMap(m)

Categories : Scala

How to give the Scala compiler evidence that a collection has elements of the correct types?
You can enable the conversions with a simple set of implicits. class JValue implicit intToJValue(x: Int) = new JValue implicit stringToJValue(x: String) = new JValue val xs: List[JValue] = List(1, "hello") For your second question you can enable wholesale list conversion with: implicit def listToJList[A <% JValue](xs: List[A]): List[JValue] = xs def foo[A <% JValue](x: List[A]): List[JValue] = x This above example only works if you have a uniform type, otherwise you will need to employ a more sophisticated means, a list of heterogeneous types will unify to List[Any] in most cases. You could come up more elegant/complicated solutions using shapeless, most employing shapless.Poly and HList's.

Categories : Scala

How to make tree implemented in Scala useful with higher-order collection functions?
Let's rename FactType to something that looks more like a type parameter. I think naming it just T helps indicate it is a type parameter versus a meaningful class in your code: sealed abstract class FactsQueryAst[T] extends Traversable[T] So FactQueryAst contains things of type T and we want to be able to traverse the tree to do something for each t:T. The method to implement is: def foreach[U](f: T => U): Unit So replacing all FactType in your code with T and modifying the signature of T, I end up with: object FactsQueryAst { case class AndNode[T](subqueries: Seq[FactsQueryAst[T]]) extends FactsQueryAst[T] { def foreach[U](f: T => U) { subqueries foreach { _.foreach(f) } } } case class OrNode[T](subqueries: Seq[FactsQueryAst[T]]) extends FactsQueryAst[T] { def f

Categories : Scala

How to add new object/ type and type to existing Collection
Pass the collection ByRef to the other procedure. Public Sub AddAnotherObject(ByRef colSecurities As Collection) Dim objOther As SomeOtherObject Set objOther = New SomeOtherObject colSecurities.Add objOther, CStr(objOther.ID) End Sub When you get back to the calling procedure, the collection's count will be one higher and the object will be in the collection. The opposite of ByRef is ByVal. Changes to a variable passed ByVal are lost once the procedure ends.

Categories : Excel

Collection of a Type using a Generic Type of any kind
Simple approach Just add another interface that is not generic: public interface IServiceInvokerUntyped { } public interface IServiceInvoker<TServiceContract> : IServiceInvokerUntyped { } Declare the dictionary it like this: private Dictionary<string, IServiceInvokerUntyped> _serviceInvocationCollection = new Dictionary<string, IServiceInvokerUntyped>(); Variant approach If your generic type parameter can be declared as covariant: public interface IServiceInvoker<out T> : IServiceInvokerUntyped { } Declare the dictionary it like this: private Dictionary<string, IServiceInvoker<object>> _serviceInvocationCollection = new Dictionary<string, IServiceInvoker<object>>(); For contravariance, just change 'out' to 'in' and modify the

Categories : C#

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

Scala type deferring
How to fix a error You have to add an implicit parameter to your method like this: def buildJsArray[T](l: List[T])(result: JsArray)(implicit tjs: Writes[T]): JsArray There is such parameter in the Json.toJson method. The reason why you have to add this parameter is that you know how to convert T to json only when you know what T is. It means you have the method to serialize T only when you call buildJsArray and this parameter allows you to pass this serialization method to the method buildJsArray. How to build a JSArray You could just use a constructor of JsArray. It takes a Seq[JsValue]: new JsArray(l.map{Json.toJson(_)}) There is already an implicit Writes for Traversable so you don't need your own method buildJsArray, you could just use method Json.toJson with parameter of typ

Categories : Scala

which collection type to use in .NET 4.5?
I'd use a dictionary with a custom key type that override GetHashCode where the result depends on the value of your handle or point coordinates. I'd also add a value wrapper class that acts as a linked-list that contains references to the next element in your chain.

Categories : Dotnet

Scala Cannot prove type equality
this.type is the type of a specific instance. It is not compatible with any other instance, even if instances of the exact same type. So basically in this definition: def -[A](other: A)(implicit evidence: this.type =:= A): this.type your evidence tries to prove that other is the exact same instance as this, which is probably not what you has in mind. I think you'll want to rework your design. You might try to use F-bounded polymorphism instead: trait Operable[Self <: Operable[Self]] { def +(other: Self): Self def -(other: Self): Self def *(other: Float): Self } /** Position descriptions */ trait Pos[T <: Operable[T]] { def eval: T } def test[T <: Operable[T]](x1: Pos[T], x2: Pos[T]): T = { x2.eval - x1.eval }

Categories : Scala

Scala and type bound with a given operation
Sure, it's possible with a structural type, and you've even almost got the syntax right: def foo(x: { def apply(): Double }) = x.apply And then: scala> foo(() => 13.0) res0: Double = 13.0 Or: scala> foo(new { def apply() = 42.0 }) res1: Double = 42.0 The definition of foo will give you a warning about reflective access, which you can avoid by adding an import or compiler option (as described in the warning message). Note that there is some overhead involved in calling methods on a structural type, so if you need this in a tight inner loop you may want to rethink your approach a bit. In most cases, though, it probably won't make a noticeable difference.

Categories : Scala

How to match scala generic type?
You could use ClassTag. val string = implicitly[ClassTag[String]] def getValue[T : ClassTag] = implicitly[ClassTag[T]] match { case `string` => "String" case ClassTag.Int => "Int" case _ => "Other" } Or TypeTag: import scala.reflect.runtime.universe.{TypeTag, typeOf} def getValue[T : TypeTag] = if (typeOf[T] =:= typeOf[String]) "String" else if (typeOf[T] =:= typeOf[Int]) "Int" else "Other" Usage: scala> getValue[String] res0: String = String scala> getValue[Int] res1: String = Int scala> getValue[Long] res2: String = Other If you are using 2.9.x you should use Manifest: import scala.reflect.Manifest def getValue[T : Manifest] = if (manifest[T] == manifest[String]) "String" else if (manifest[T] == manifest[Int]) "

Categories : Scala

Scala Pickling and type parameters
Looking at the project, it seems you need either an scala.pickling.SPickler or a scala.pickling.DPickler (static and dynamic, respectively) in order to pickle a particular type. The pickle methods are macros. I suspect that if you pickle with an SPickler, the macro will require the compile time type of your class to be known. Thus, you may need to do something similar to: object Foo { def bar(t: SomeClass1) = t.pickle def bar(t: SomeClass2) = t.pickle def bar(t: SomeClass3) = t.pickle // etc } Alternatively, a DPickler may do the trick. I suspect that you'll still have to write some custom pickling logic for your specific types.

Categories : Scala

Scala Advanced Type Usage
Without more details on your DSL, I'm afraid it's not clear what you mean by "access the tuple types statically". Here's a simplified version of the API that has no trouble with tuple types: class Event[T] { def joinOn[T2, R](ev2: Event[T2])(f: (T, T2) => R) = new Event[R] } You can use this as follows: val e1 = new Event[(Int, String)] val e2 = new Event[(Int, String)] val e3 = e1.joinOn(e2)(_._1 == _._2) It should be easy to see how this could be extended to supporting your join/windowLength/on syntax. Update: I can see that your use case is complicated by the fact that you need to translate the Scala-encoded query expression to another query language. In this case, you want the on method's signature to look like: def on[T2, R](f: (Expr[T], Expr[T2]) => Expr[R]): Event[R

Categories : Scala

Scala's "clean up" of type erasure
Well, the quote says “cleans up”, not “eliminates”. Type erasure is still there and it can bite you. Scala has Manifests. Manifest is an object containing information about your actual type. Here is a nice answer about Manifests.

Categories : Scala

why does scala toString give type Any?
What happens if q >= 3 ? What type does if return then ? e.g. if you write this: if (qqq < 0) "a" else "b" you'll always get a String return type

Categories : String

Type mismatch in scala with wildcards
Without further information this answer is only a guess based on the error: type mismatch; found : TBase[_$1,_$2] where type _$2, type _$1 required: TBase[_ <: TBase[_, _], _ <: TFieldIdEnum] Constraining the type arguments as the error message suggested may fix the problem: def serialize(base: TBase[_ <: TBase[_,_] ,_ <: TFieldIdEnum]) It's hard to tell why this would be case, without seeing the signatures of the serialize methods and the TBase class. I can only speculate that the java wildcards brings the constraint already defined somewhere else, while the scala existencials doesn't, requiring that you state than explicitly. Also, don't use the return keyword. It doesn't do what you think it does.

Categories : Java

Scala really weird Type Mismatch
You already have type parameter A on the original 'dropWhile' which is scoping the type of f. However, you then introduce a second type parameter on the inner def which shadows the outer definition of A and scopes the type of the XList. So the problem is that the A are not the same type! If you remove the shadowed type, it all works (few other changes made to get your code to compile): def dropWhile[A](l: XList[A])(f: A => Boolean): XList[A] = { def dropWhile(toCheck: XList[A], toKeep: XList[A]) : XList[A] = toCheck match { case XNil => toKeep case Cons(h, t) if f(h) == false => dropWhile(t, Cons(h, toKeep)) case Cons(_, Cons(t1, t2)) => dropWhile(Cons(t1, t2), toKeep) } dropWhile(l, XNil) }

Categories : Scala

Clojure to Scala type conversions
Because Clojure and Scala both run on the JVM, this is fairly straight-forward: (ns scala-from-clojure.core (:import (scala.collection JavaConversions))) (defn to-scala-seq [coll] (-> coll JavaConversions/asScalaBuffer .toList)) At the REPL user=> (use 'scala-from-clojure.core) nil user=> (to-scala-seq [1 2 3]) #<$colon$colon List(1, 2, 3)> user=> (instance? scala.collection.immutable.Seq *1) true See How to create a scala.collection.immutable.Seq from a Java List in Java?

Categories : Scala



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