在 Scala 中,我们可以使用 implicitly
关键字来捕捉到多个隐式值。下面是一个示例代码:
trait Show[T] {
def show(t: T): String
}
object Show {
implicit val showInt: Show[Int] = (t: Int) => t.toString
implicit val showString: Show[String] = (t: String) => t
implicit val showBoolean: Show[Boolean] = (t: Boolean) => t.toString
}
def print[T](t: T)(implicit show: Show[T]): Unit = {
println(show.show(t))
}
def main(args: Array[String]): Unit = {
implicit val showDouble: Show[Double] = (t: Double) => t.toString
print(42) // 使用隐式值 Show.showInt
print("Hello") // 使用隐式值 Show.showString
print(true) // 使用隐式值 Show.showBoolean
print(3.14) // 使用隐式值 showDouble(在 main 方法中定义)
}
在上面的代码中,我们定义了一个 Show
类型类,它定义了一个 show
方法用于将值转换为字符串。我们还定义了一些隐式值,用于提供不同类型的 Show
实例。
在 print
方法中,我们使用了隐式参数 show
来获取对应类型的 Show
实例。当我们调用 print
方法时,编译器会查找当前作用域内的适合的隐式值来填充这个参数。
在 main
方法中,我们又定义了一个额外的隐式值 showDouble
,用于提供 Double
类型的 Show
实例。当我们调用 print(3.14)
时,编译器会使用这个隐式值。
因此,输出结果将会是:
42
Hello
true
3.14