相关疑难解决方法(0)

为什么Scala方法的显式调用允许隐式解析?

为什么此代码无法编译,但在取消注释指示的行时成功编译?(我每晚都使用Scala 2.8).似乎显式调用string2Wrapper允许从该点隐式使用它.

class A {
  import Implicits.string2Wrapper
  def foo() {
     //string2Wrapper("A") ==> "B" // <-- uncomment
  } 
  def bar() {
    "A" ==> "B"
    "B" ==> "C"
    "C" ==> "D"
  }
  object Implicits {
    implicit def string2Wrapper(s: String) = new Wrapper(s)
    class Wrapper(s: String) {
      def ==>(s2: String) {}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:感谢目前为止的答案,其中包括指向Martin Odersky评论的指针,

"没有显式结果类型的隐式转换只能在自己定义的文本中可见.这样,我们就避免了循环引用错误."

我仍然有兴趣找出1)"循环参考错误"的危险是什么?,2)为什么显式调用有什么不同?

scala implicit scala-2.8

16
推荐指数
2
解决办法
8198
查看次数

当类型类不在专用源文件中时,为什么Scala不能在伴随对象中隐式定义我的类型类实例?

请参阅下面的源代码.所有源代码都在同一个包中定义.当我定义一个源文件中的所有代码ShowMain.scala,我得到一个编译错误,但是当object ShowMain在被定义ShowMain.scalatrait Showobject Show中定义Show.scala,也没有编译错误.

我的问题: 这是什么原因?我遇到了什么语言规则?

示例代码:

object ShowMain {

  def main(args: Array[String]): Unit = {
    output("hello")
  }

  def output[A](a: A)(implicit show: Show[A]) =
    println(show.show(a))

}

trait Show[-A] {
  def show(a: A): String
}

object Show {

  implicit object StringShow extends Show[String] {
    def show(s: String) = s"[String: $s]"
  }

}
Run Code Online (Sandbox Code Playgroud)

编译错误:

(ScalaIDE/Scala 2.11.2在线包含output("hello"))

Multiple markers at this line
    - not enough arguments for method output: …
Run Code Online (Sandbox Code Playgroud)

scala implicit typeclass companion-object

1
推荐指数
1
解决办法
859
查看次数

标签 统计

implicit ×2

scala ×2

companion-object ×1

scala-2.8 ×1

typeclass ×1