我正在尝试使用宏实现自定义字符串插值方法,我需要一些关于使用API的指导.
这是我想要做的:
/** expected
* LocatedPieces(List(("\nHello ", Place("world"), Position()),
("\nHow are you, ", Name("Eric"), Position(...)))
*/
val locatedPieces: LocatedPieces =
s2"""
Hello $place
How are you, $name
"""
val place: Piece = Place("world")
val name: Piece = Name("Eric")
trait Piece
case class Place(p: String) extends Piece
case class Name(n: String) extends Piece
/** sequence of each interpolated Piece object with:
* the preceding text and its location
*/
case class LocatedPieces(located: Seq[(String, Piece, Position)])
implicit class s2pieces(sc: StringContext) {
def …Run Code Online (Sandbox Code Playgroud) 当反射仍然开始时,在Scala 2.10.0里程碑的时代,我问了一个问题,我怎么能用它来查看REPL的代码片段树.优秀的答案比我的要求更进一步,并展示了它们如何用于解析和评估树木,所以我继续尝试将它用于我今天进行的一个小项目.
不幸的是,以这种方式解析和评估的代码似乎没有看到任何REPL定义:
scala> val x = 1
x: Int = 1
scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox
scala> val tb = scala.reflect.runtime.universe.runtimeMirror(
getClass.getClassLoader).mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = ...
scala> tb.eval(tb.parse("x"))
scala.tools.reflect.ToolBoxError: reflective compilation has failed:
not found: value x
Run Code Online (Sandbox Code Playgroud)
有没有办法让它识别REPL上的定义?
我正在编写一个库来通过API访问Web服务.我已经定义了简单的类来表示API动作
case class ApiAction[A](run: Credentials => Either[Error, A])
Run Code Online (Sandbox Code Playgroud)
和一些执行Web服务调用的函数
// Retrieve foo by id
def get(id: Long): ApiAction[Foo] = ???
// List all foo's
def list: ApiAction[Seq[Foo]] = ???
// Create a new foo
def create(name: String): ApiAction[Foo] = ???
// Update foo
def update(updated: Foo): ApiAction[Foo] = ???
// Delete foo
def delete(id: Long): ApiAction[Unit] = ???
Run Code Online (Sandbox Code Playgroud)
我也做ApiAction了一个单子
implicit val monad = new Monad[ApiAction] { ... }
Run Code Online (Sandbox Code Playgroud)
所以我可以做点什么
create("My foo").run(c)
get(42).map(changeFooSomehow).flatMap(update).run(c)
get(42).map(_.id).flatMap(delete).run(c)
Run Code Online (Sandbox Code Playgroud)
现在我有麻烦测试它的monad法律
val x = 42 …Run Code Online (Sandbox Code Playgroud)