score:5

Accepted answer

In short, you can't.

Here are your options:

Forwarding implicits

Say you have a function that executes a Future and you need an ExecutionContext: You can either import scala.concurrent.ExecutionContext.Implicits.global(or define your own etc) in the same file as someFun, and you get this:

import scala.concurrent.ExecutionContext.Implicits.global
def someFun(): Future[SomeThing] = {
  Future(something)
}

Or if you don't want to import in the same file(class, object etc) as someFun, you forward the implicit. This way, you can import it when you use someFun in another file.

def someFun()(implicit ex: ExecutionContext): Future[SomeThing] {
   Future(someThing)
}

Context bounds

Sounds like this is what you want, only you didn't implement it properly.

class Stub[T](name: String)
def myFunc[T: Moo](stub: Stub[T]) = {
  println(stub + " " + implicitly[Moo[String]])
}

The above is the equivalent of:

def myFunc[T](stub: T)(implicit evidence: Moo[T]) = {
  println(stub + " " + evidence.toString)
}

View bounds

Alternatively, if it makes more sense to implicitly convert a Stub to a Moo rather than bound it:

def myFunc[T <% Moo](stub: T) = {
  println(stub + " " + implicitly[Moo[T]])
}

To use the above, you need to provide materialized implicits(e.g a way to convert a stub to a Moo). For example:

implicit def stubToMoo[T](stub: Stub[T]): Moo[T] = {
  new Moo(stub) // or whatever
}

Bottom line, in your question usage of implicits makes no sense whatsoever. You can do the "thin-air" import as you describe, but based on the options above, see if it's worth it.

score:0

Then there is no need to declare it implicit. Consider this:

object B {
  val moo = "World!"
}

...

import B._

object A {
  def myFunc(stub: String) {
    println(stub + " " + moo)
  }
}

myFunc("Hello")

Related Query

More Query from same tag