小编Rhe*_*ese的帖子

为什么这个简单的隐式stringToInt函数会导致堆栈溢出?

如果我定义一个简单的stringToInt函数并将其存储为val,那么一切都按预期工作,例如

scala> def stringToInt1: (String => Int) = _.toInt
stringToInt1: String => Int

scala> stringToInt1("1")
res0: Int = 1
Run Code Online (Sandbox Code Playgroud)

但是,如果我然后隐藏它,它会导致堆栈溢出:

scala> implicit def stringToInt2: (String => Int) = _.toInt
stringToInt2: String => Int

scala> stringToInt2("1")
java.lang.StackOverflowError
at .stringToInt2(<console>:7)
at $anonfun$stringToInt2$1.apply(<console>:7)
at $anonfun$stringToInt2$1.apply(<console>:7)
...
Run Code Online (Sandbox Code Playgroud)

起初我怀疑这是因为下划线没有解决我的预期,但情况并非如此,因为这种隐式val的样式适用于以下简单函数:

scala> implicit def plusTwo: (Int => Int) = _ + 2
plusTwo: Int => Int

scala> plusTwo(2)
res2: Int = 4
Run Code Online (Sandbox Code Playgroud)

如果我显式定义参数,没有堆栈溢出:

scala> implicit def stringToInt3(s: String) = s.toInt
stringToInt3: (s: String)Int

scala> stringToInt3("1")
res3: Int …
Run Code Online (Sandbox Code Playgroud)

scala implicit scala-2.10

5
推荐指数
1
解决办法
214
查看次数

标签 统计

implicit ×1

scala ×1

scala-2.10 ×1