在Scala工作表中的随播对象中找不到隐式值 [英] Could not find implicit value inside companion object in Scala Worksheet

查看:73
本文介绍了在Scala工作表中的随播对象中找不到隐式值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在IntelliJ Scala工作表中创建一个类型类.所以我从这样的特质开始

I am trying to create a type class inside IntelliJ Scala Worksheet. So I started with trait like this

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

并创建了一个随播对象

object Show {

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

  implicit val intCanShow: Show[Int] =
    new Show[Int] {
      def show(int: Int): String = s"int $int"
    }

}

当我尝试

println(Show.show(20))

我收到此错误.

Error:(50, 26) could not find implicit value for parameter sh: Show[Int]
println(Show.show(20))

但是当我从对象Show中取出intCanShow时,它可以正常工作.为什么不能scala访问对象内部的隐式?

But when I take the intCanShow out of the object Show, it works fine. Why cannot scala acess the the implicit inside the object?

推荐答案

作为scala脚本运行时,您的示例可以按预期工作.
在名为test.sh并标记为可执行文件

Your example appears to work as expected when run as a scala script.
With the following in a file named test.sh and marked executable

#!/usr/bin/env scala
trait Show[A] {
  def show(a : A) : String
}
object Show {
  def show[A](a: A)(implicit sh: Show[A]) = sh.show(a)

  implicit val intCanShow: Show[Int] =
    new Show[Int] {
      def show(int: Int): String = s"int $int"
    }
}

println(Show.show(20))

我观察

bash-3.2$ ./test.sh
int 20

这篇关于在Scala工作表中的随播对象中找不到隐式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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