FAQ Database Discussion Community


Unexpected implicit resolution in scala

scala,types,implicit,type-level-computation
I was trying to work out some simple examples of type-level programming in Scala 2.11. Here is a function to tell type equality: def type_==[A, B](implicit ev: A =:= B = null) = ev != null Here =:= is defined in the prelude, but for our purpose, even a simple...

Can't overload apply method in Scala Implicit class

scala,apply,implicit
I am writing a retry function with async and await def awaitRetry[T](times: Int)(block: => Future[T]): Future[T] = async { var i = 0 var result: Try[T] = Failure(new RuntimeException("failure")) while (result.isFailure && i < times) { result = await { Try(block) } // can't compile i += 1 } result.get...

Different behaviours in cast operations? [duplicate]

c#,casting,implicit,explicit,sender
This question already has an answer here: What is the difference between a reference type and value type in c#? 10 answers Could anyone please explain to me why ,in those two casting scenarios below, the casted variables acts different? While first variable (double initial) preserves its initial value...

How can I 'discover' type classes/implicit values in the current scope?

scala,typeclass,read-eval-print-loop,implicit
I've made use of a few of scala's built-in type classes, and created a few of my own. However, the biggest issue I have with them at the moment is: how do I find type classes available to me? While most of those that I write are small and simple,...

impicit Ordering and covariance

scala,implicit
class Foo class Bar extends Foo implicit val ord = new math.Ordering[Foo] { override defcompare(a: Foo, b: Foo) = 0 } When trying to summon the Ordering instance of Bar implicitly[math.Ordering[Bar]] it fails with No implicit Ordering defined for Bar. I expected it to pick up the instance I defined...

Can I define Haxe implicit cast behaviour for a class?

class,casting,haxe,implicit
is it possible to define implicit cast behaviour? For instance, I have a class Color class Color { public var r: Int; public var g: Int; public var b: Int; public function new(?r: Int = 0, ?g: Int = 0, ?b: Int = 0) { this.r = r; this.g =...

How to override an implicit value?

scala,implicit,scala-2.11
Suppose I have the code: class A(implicit s:String = "foo"){println(s)} object X { implicit val s1 = "hello" } object Y { import X._ // do something with X implicit val s2 = "hi" val a = new A } I get the error: <console>:14: error: ambiguous implicit values: both...

In Scala, how to define a implicit value/parameter in companion object?

scala,session,implicit
I saw codes below from this Link abstract class SessionFactory { protected[squery] def createConnection(): Connection def createSession(): Session = new Session(this) def withSession[T](f: Session => T): T = { val s = createSession() try { f(s) } finally s.close() } def withSession[T](f: => T): T = withSession { s: Session...

Translate/encode Haskell's `data Obj = forall a. (Show a) => Obj a` in Scala

scala,haskell,typeclass,implicit,existential-type
I've not been able to come up with how to encode Obj in Scala: {-# LANGUAGE ExistentialQuantification #-} data Obj = forall a. (Show a) => Obj a instance Show Obj where show (Obj a) = "Obj " ++ show a main = print $ show [Obj "hello", Obj 3,...

How to Supress implicit return from a closure with Void return type in Swift

swift,return,closures,implicit,completion-block
lets consider we have a closure like: (used as completionHandler) func doSomething (completionHandler : (done : Bool)->Void )->Void { ... completionHandler(true) } now if we want to do something like that : doSomething({ (done : Bool)-> Void var data : NSDictionary = NSDictionary() data.setValue("data1", forKey: "data1") // 1 data.setValue("data2", forKey:...

Scala: How to make toString() take an implicit parameter?

scala,implicit
I would like to be able to have a case class like this: case class TxtFrag(start:Int, end:Int){ override def toString()(implicit src:String) = src.substring(start, end) } so that I can do something like this: implicit val sourceText = "FooBar" println(TxtFrag(0, 3)) // should print "Foo" But, understandably, the compiler complains that...

Good way to automate user login and keep the user information in Play Framework

scala,playframework-2.0,implicit
First of all, I'm still a newbie in scala, so this question can seem pretty basic, or maybe my approach is wrong, but I couldn't figure out how to do this: I've integrated Oauth2 authentication into my project and now I'm trying to automatize the login, so instead of writting...

Change a picture inside app using camera

android,android-intent,camera,contact,implicit
Excuse me everyone. I'm sorry if my english not good, I can't speak english well :) . I want to make an android app and its look like contact app. When opening the app there are some people's name. When I click a name it will open details activity. Inside...

No implicit format for MyClass available using Json.format

json,scala,playframework-2.0,implicit
I'm getting an error when using a complex object as attribute of another object on Json.format. I have two classes: RoleDTO and EmailInvitationDTO. EmailInvitationDTO has a RoleDTO. So, I declared: case class RoleDTO(id:Option[Long] = None, roleType:Int, userID:Long, fromHousingUnitID:Option[Long] = None, isAdmin:Option[Boolean] = None, fromResidentUserID:Option[Long] = None, documentNumber:Option[String] = None, fromCondoID:Option[Long]...

How to use specific apply method in implicit Json `reads` from Scala

json,scala,implicit
I have a class that takes a few optional Enumeration types in its constructor: case class GPMedia(id: Option[GPID], created: Option[DateTime], active: Option[Boolean], data: Array[Byte], mimeType: Option[GPMediaType.Type], encoding: Option[GPEncoder.Codec], compression: Option[GPCompressor.Type]) I've been struggling to create an implicit Json reads method that works. I keep ending up with errors such as:...

Implicit conversion works for symbol but not string

scala,implicit
I'm working on a DSL for some formal grammar based stuff. I'd like to be able to say something like 'start produces "a" andThen 'b andThen "c", where symbols and strings represent different components of the grammar. I'm seeing a problem with code like this: class ImplicitTest { trait GrammarPart...

Scala activerecord with implicit json format

json,scala,activerecord,implicit
I have a scala-activerecord: case class Person(name: String) extends ActiveRecord with Timestamps object Person extends ActiveRecordCompanion[Person] Everything works ok. Suddenly, I want to provide an API and repond with json representation of the entity, so I modified the code: case class Person(name: String) extends ActiveRecord with Timestamps object Person extends...

scala macros generating implicits

scala,macros,implicit,scala-macros
I am trying to generate some implicits via a macro -the condensed version of the macro looks like this: object Implicits { def generate(c:Context):c.Expr[Unit]={ import c.universe._ c.Expr[Unit] { q""" object Dud{ implicit val p:java.io.File = new java.io.File("/tmp") def toString():String ={ "Dud here" } } import Dud._ """ } } }...

Constructing a value through two implicit constructors?

c++,constructor,implicit
TLDR: I have two templatized classes Outer and Inner. Inner<X> can be implicitly constructed from X, and Outer<Y> can be implicitly constructed from Y. Should Outer<Inner<X>> = X() work? More details: Suppose I have the following two classes: template<typename T> class Inner { public: Inner(const T& value) {} Inner(T&& value)...

Scala Typeclasses with generics

scala,generics,implicit-conversion,typeclass,implicit
I've been playing with the typeclass pattern in Scala, but I haven't been able to figure out how to implement the implicit companion object when the type I'm working with is generic. For example, let's say I've defined a trait for a typeclass that provides functions for putting things into...

implicit resolution for a function argument

scala,implicit,context-bound
I tried to implement mergesort in Scala. I got to the following: def mergeSort[A: Ordering](as: List[A]): List[A] = as match { case Nil => as case head :: Nil => as case _ => { val (l, r) = split(as) merge(mergeSort(l), mergeSort(r)) } } def split[A](as: List[A]): (List[A], List[A]) =...

Why do we need the From type parameter in Scala's CanBuildFrom

scala,implicit
I am experimenting with a set of custom container functions and took inspiration from Scala's collections library with regard to the CanBuildFrom[-From, -Elem, -To] implicit parameter. In Scala's collections, CanBuildFrom enables parametrization of the return type of functions like map. Internally the CanBuildFrom parameter is used like a factory: map...

Implicit def type classes from other type classes

scala,typeclass,implicit,companion-object,implicit-typing
I want to add a new implicit type class Divisible for every type T that already has either an implicit Fractional or Integral type classes. The code I wrote does not compile: object Divisible { implicit def fractionalDivisible[T](implicit frac: Fractional[T]): Divisible[T] = new Divisible[T] { override def div(x: T, y:...

C++ implicit and explicit inheritance constructor calls

c++,inheritance,implicit,explicit
I have a question about implicit and explicit calls to a base constructor. If we have a class hierarchy like this: class Person{ protected: std::string m_name; public: Person(std::string& _name) : m_name(_name){std::cout << "A person is being constructed." << std::endl;} }; class Baby : public Person{ private: int m_no_of_nappies; public: Baby(std::string&...

Introduce implicit methods/fields into anonymous function

scala,implicit
I'm just getting started with Scala and I got stuck trying to create one particular object. I have an object IdentifierFactory that I want to use to generate an Identifier instance. I have defined it like so: object IdentifierFactory { def apply(f: => Any):Identifier = { f; validate Identifier(...) }...

`implicit' modifier cannot be used for top-level objects

scala,implicit
I recently started to work on play & reactive mongo. Referred the reactive mongo documentation to create a SimpleAlbum. When I run the play app I am getting an error like "Implicit modifier cannot be used for top-level objects". Why am I getting this? Help me in resolving the issue....

Resolving Implicit for `Show` Typeclass Instance

scala,implicit
I'm trying to make Gender implement the Show typeclass. scala> trait Gender extends Show[Gender] defined trait Gender scala> case object Male extends Gender defined object Male scala> case object Female extends Gender defined object Female Next, I defined a function that calls show on an implicit Show[A]. scala> def f[A...