什么 Scala 功能允许在 Any 上使用加号运算符? [英] What Scala feature allows the plus operator to be used on Any?

查看:31
本文介绍了什么 Scala 功能允许在 Any 上使用加号运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习 Scala,当我在 Koans 中遇到一个示例时,我无法理解它为什么起作用:

I'm still learning Scala, and when I ran across an example in the Koans, I wasn't able to understand why it works:

var foo : Any = "foo"
println(foo + "bar")

Any 没有 + 方法

Any doesn't have a + method

推荐答案

scala.Predef 对象:

implicit def any2stringadd(x: Any): StringAdd

StringAdd 定义了一个 + 操作符/方法:

StringAdd defines a + operator/method:

def +(other: String) = String.valueOf(self) + other

此外,由于 scala.Predef 始终在范围内,因此隐式转换将始终有效.

Also, since scala.Predef is always in scope, that implicit conversion will always work.

这篇关于什么 Scala 功能允许在 Any 上使用加号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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