是否可以在Scala解释器中定义伴随类/模块?

Aar*_*rup 4 scala

在Scala解释器中测试内容通常很方便.但是,我遇到的一个问题是我必须重构使用隐式转换的代码,因为定义一个与现有类同名的对象并不会使它成为REPL中的伴随模块.结果,当我翻译回"真正的来源"时,我无法确信我的代码仍然有效.

有没有办法在REPL中定义伴侣?也许是一些类似的东西

bigblock {
   class A

   object A {
      implicit def strToA(s: String): A = // ... 
   }
}
Run Code Online (Sandbox Code Playgroud)

这样的

val v: A = "apple"
Run Code Online (Sandbox Code Playgroud)

将编译.

Ran*_*ulz 11

那很接近:

object ABlock {
   class A

   object A {
      implicit def strToA(s: String): A = // ... 
   }
}
import ABlock._
Run Code Online (Sandbox Code Playgroud)

或者,如果您将所有内容放在一行上,请执行以下操作:

class A; object A { implicit def strToA(s: String): A = // ... } }
Run Code Online (Sandbox Code Playgroud)

...尽管如此,您仍然需要导入隐式转换,以便按照您的要求进行以下工作:

import ABlock.A.strToA  // for the form with the enclosing object
import A.strToA         // for the one-line form without an enclosing object
val v: A = "apple"
Run Code Online (Sandbox Code Playgroud)

您需要这样做的原因是您在REPL中输入的每一行都包含在一个对象中,而后续的每一行都嵌套在前一个对象中.这样做是为了您可以执行以下操作而不会出现重新定义错误:

val a = 5
val a = "five"
Run Code Online (Sandbox Code Playgroud)

(实际上,a这里的第二个定义会影响第一个.)