scala - 在 scala 中将 Int 添加到字符串

标签 scala types casting return-value return-type

我在理解以下几段 scala 代码背后的基本原理时遇到了一些困难:

我们都知道 REPL 中的 1 + 1 = 2。

scala> 1 + 1
res0: Int = 2

如果我输入“Abc”+“Def”,我应该在 REPL 中得到“AbcDef”。

scala> "Abc" + "Def"
res6: java.lang.String = AbcDef

现在假设我在字符串“Abc”上调用 + 方法并传递“Def”作为参数:

scala> "Abc".+("Def")
res7: java.lang.String = AbcDef

同样的道理,为什么像 1.+(1) 这样的东西会返回一个 double 的 2.0?

scala> 1.+(1)
res1: Double = 2.0

另外,为什么将参数“1”作为参数传递会导致“1.01”,如下所示:

scala> 1.+("1")
res9: String = 1.01

为什么返回的结果是 String 而不是我将“1”转换为调用者类型?

谢谢

最佳答案

如果您在 Scala 2.10.0 上尝试一下,您就会得到答案的线索:

scala> 1.+(1)
<console>:1: warning: This lexical syntax is deprecated.  From scala 2.11,
             a dot will only be considered part of a number if it is immediately
             followed by a digit.
       1.+(1)
       ^

简单地说,1. 在 Scala 中是有效的 Double(就像在 Java 中一样),所以 Scala 确实是这样做的:

1.  +  (1)

也就是说,将 Double 中缀加到包含在(冗余)括号内的表达式中。

对于后者,Scala 遵循 Java 约定,即任何添加到 String 的内容都会生成 String,反之亦然。

关于scala - 在 scala 中将 Int 添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14807919/

相关文章:

c - 奇怪的不兼容指针类型错误

c++ - 在 C++ 中应该使用什么来检查身份?

c++ - 在不更改基类的情况下将一个派生类转换为另一个派生类

java - 在 Android 中转换 AsyncTask

scala - 将 Either[A, B] 转换为 Option[A],其中 Left 变为 Some

斯卡拉编程环境

java - 从 Java Integer 到 Scala Int : toInt vs unbox? 的正确方法

java - 当您在不指定对象类型的情况下创建 ArrayList 时,它会在您添加第一个对象时自动创建它吗?

types - 用于类型推断的 OCaml LET REC 键入规则

scala - Play 2.x : Reactive file upload with Iteratees