def flatMap[B](f: A => IO[B]): IO[B] = new:
def unsafeRun = f(self.unsafeRun).unsafeRun
该方法创建一个新的IO对象
我不明白没有类型的 new 的用法。感觉像是结构类型,但不太确定。我刚刚开始过渡到 scala 3。
您所描述的是 Scala 3 的一项新功能,如果可以推断类型,它允许您在创建某个类的匿名实例时删除类型名称:
trait Foo {
def a(i: Int): String
}
// this is what Scala 2 requires
val foo1: Foo = new Foo {
def a(i: Int): String = i.toString
}
// this is what Scala 3 allows
val foo2: Foo = new { // Foo in inferred from variable type
def a(i: Int): String = i.toString
}
// this is what Scala 3 with braceless syntax
val foo3: Foo = new:
def a(i: Int): String = i.toString
您甚至可以在某些嵌套上下文中使用它,例如:
trait Foo:
def a(i: Int): String
trait Bar:
def foo: Foo
val bar = new:
def foo: Foo = new:
def a(i: Int): String = i.toString
但它几乎立即变得不可读,这就是为什么此演示将其归类为 Scala 3 特定反模式。
这可能是破解一些快速脚本的好方法,但请避免在较大的长期代码库中使用它。