Skip to content

Some sort of sourcecode.Caller[T] implicit #9

Open
@lihaoyi

Description

@lihaoyi

Use cases:

  • Getting the caller for logging or something:
object Foo{
  def log()(implicit caller: sourcecode.Caller[Any]) = {
    println(caller.value)
  }
}
object Bar{
  Foo.log() // Bar
}
  • Restricting who you can be called from
class IKnowWhatImDoing
object Foo{
  def runDangerous()(implicit caller: sourcecode.Caller[IKnowWhatImDoing]) = {
    println(caller.value)
  }
}
object Bar {
  Foo.runDangerous() // compile error
}
object Bar2 extends IKnowWhatImDoing{
  Foo.runDangerous() // ok, prints Bar2
}
  • Getting calling class or classloader, e.g. for loading resources, without needing to worry about properly setting up and tearing down the Context ClassLoader:
object Foo{
  def getResource(path: String)(implicit caller: sourcecode.Caller[_]) = {
    caller.value.getClass.getClassLoader.getResourceAsStream(path)
  }
}
object Bar{
  Foo.getResource("/thing/file.txt") // loads resource from `Bar`s classloader, always
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions