Scala 通用函数假设类型

标签 scala

当尝试定义泛型方法时 def f[T] (x:T) = x + 1 Scala 给出以下错误

<console>:8: error: type mismatch;
found   : Int(1)
required: String
   def f[T] (x:T) = x + 1
                        ^

问题是为什么 Scala 假设它应该是一个 String

如果我们想要一个可以对 IntCharString 执行 +1 的函数,该怎么办?我知道我可以执行如下操作,但它仅适用于 IntChar

def f[T <% Int](x:T) = x + 1

那么这个错误的原因是什么以及如何以通用方式处理它。

最佳答案

The question is why Scala is assuming that it should be a String?

我不能保证这个分析,但 Scala 似乎正在将 Predef.any2stringadd() 隐式转换应用于 x,试图将其转换为支持 + 运算符的东西。

这是一个可以编译的变体,它演示了隐式转换:

scala> def f(x:Any) = { x + "1" }
f: (x: Any)String

scala> f("foo")
res3: String = foo1

scala> f(123)
res0: String = 1231

scala> f(classOf[String])
res2: String = class java.lang.String1

What if we want a function that can do +1 to Int, Char and String.

给这些值加 1 是什么意思?

如果您只想调用+运算符,则需要使用match运算符根据实际类型选择不同的行为。这是因为,虽然名称 + 用于两者,但字符串和数字之间没有共同的行为。

另一方面,也许您想要处理可以作为字符串或数值提供的数字(在这种情况下,为什么使用 Char?)。为了实现这一点,您需要一个将 Any 转换为数字的隐式函数。

scala> implicit def any2int(x:Any) : Int = { x.toString.toInt }
warning: there were 1 feature warning(s); re-run with -feature for details
any2int: (x: Any)Int

scala> def f(x:Any) : Int = { x + 1 }
f: (x: Any)Int

scala> f(123)
res0: Int = 124

scala> f("123")
res1: Int = 124

关于Scala 通用函数假设类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566342/

相关文章:

Scala 编码标准 : curly braces on the same line

json - DataType.fromJson() 错误 : java. lang.IllegalArgumentException:无法将 JSON 字符串 'int' 转换为数据类型

scala - 选择最具体的子类型的隐式解析

scala - 将 Spark 数据帧插入 hbase

Scala:具有复杂结构的树插入尾递归

scala - 用 Scala 编写一个实用且实用的图像处理库

scala - Spark 中的循环分区是如何工作的?

java - Scala/Java servlets : How to output < in the HTML code instead of &lt;

scala - 未调用 future 的 onComplete 回调

scala - Play 2.0 Framework (scala) 中的异步结果