在Scala中导入特定的方法签名 [英] Import specific method signature in Scala

查看:92
本文介绍了在Scala中导入特定的方法签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以导入特定方法签名?

Is there a manner to import a specific method signature?

def test() {
  lazy val log = LoggerFactory.getLogger("AndroidProxy")
  import log.{error, debug, info, trace}

  trace("This is a test")
  trace "This is also"   // <- This line will not compile 
}

也许不可能,但是我的主要目标是允许这样做而无需添加新方法.我尝试了这些都没用

Perhaps it's not possible, but my primary goal is to allow this without adding in a new method. I've tried these to no avail

import log.{error => error(_:String)}
import log.{error(x: String) => error(x)}

我认为主要的挑战是所有方法都采用一个参数.我可以不使用()来调用无参数方法,并且我可以创建一系列方法调用来省略. foo getX toString,但我不知道如何自动创建arity-1呼叫

I suppose the primary challenge is that all of the methods take one argument. I can call no-argument methods without (), and I can create a chain of method calls that omits the .'s e.g. foo getX toString, but I don't know how to create an arity-1 call automatically

这是对此问题的跟踪.

推荐答案

代码存在问题:

trace "This is also"   // <- This line will not compile 

不是不是,因为您以某种方式导入了太多的trace重载变体-这是您无法以这种方式使用Scala的中缀表示法.像这样的表达式:

is not that you're somehow importing too many overloaded variants of trace - it's that you can't use Scala's infix notation this way. An expression like:

e op

被解释为"Postfix操作"(请参见 Scala语言规范),等效于调用:

is interpreted as a "Postfix Operation" (see section 6.12.2 of the Scala Language Specification), equivalent to the call:

e.op

因此您的代码将等效于:

So your code would be equivalent to:

trace."This is also"

这当然是编译错误.

如果您改为使用格式为e1 op e2的修复操作"( Scala语言规范),那么即使方法被重载也没有任何问题:

If you instead use an "Infix Operation" of the form e1 op e2 (section 6.12.3 of the Scala Language Specification), then there aren't any problems even if the method is overloaded:

scala> class Logger { def trace(s: String) = "1arg"; def trace(i: Int, s: String) = "2arg" }
defined class Logger

scala> val log = new Logger
log: Logger = Logger@63ecceb3

scala> log trace "This is also"
res0: String = 1arg

这篇关于在Scala中导入特定的方法签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆