简体   繁体   English

Scala隐式参数绑定

[英]Scala Implicit parameter bound

I'm struggling with the following problem which throws an error at compile-time " error: value dir is not a member of type parameter A". 我正在努力解决以下在编译时抛出错误的问题“错误:值dir不是类型参数A的成员”。 But it is! 但它是!

trait Logger { def dir: String }

trait LoggerFile[A <: Logger] {
  def extractor: String => Option[A]
}

def getHistory[A: LoggerFile](): String = {
  implicitly[LoggerFile[A]].extractor("abc") match {
    case Some(a) => a.dir
    case None => ""
  }
}

I was able to overcome the problem by using this answer : 我能够通过使用这个答案克服这个问题:

def getHistory[A <: Logger]()(implicit env: LoggerFile[A]): String = {

But I would have preferred the system to work before the transformation, ie with the syntactic sugar. 但我希望系统在转换之前工作,即使用语法糖。 Is there a way to specify multiple type constraints on A? 有没有办法在A上指定多个类型约束?

Just put all the constraints together. 只需将所有约束放在一起。

After changing the type signature to 将类型签名更改为

def getHistory[ A <: Logger : LoggerFile ](): String

your example compiles just fine. 你的例子编译得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM