考虑下面的代码片段
val myString =
"""
|a=b
|c=d
|""".stripMargin
Run Code Online (Sandbox Code Playgroud)
我想将其转换为带有分隔符的单行;
a=b;c=d;
Run Code Online (Sandbox Code Playgroud)
我试过
myString.replaceAll("\r",";")
Run Code Online (Sandbox Code Playgroud)
和
myString.replaceAll("\n",";")
Run Code Online (Sandbox Code Playgroud)
但没有成功。
如何转换List[Either[String, Int]]为Either[List[String], List[Int]]使用类似于cats sequence的方法?例如, xs.sequence在以下代码中
import cats.implicits._
val xs: List[Either[String, Int]] = List(Left("error1"), Left("error2"))
xs.sequence
Run Code Online (Sandbox Code Playgroud)
返回,Left(error1)而不是required Left(List(error1, error2))。
凯文·赖特的答案表明
val lefts = xs collect {case Left(x) => x }
def rights = xs collect {case Right(x) => x}
if(lefts.isEmpty) Right(rights) else Left(lefts)
Run Code Online (Sandbox Code Playgroud)
哪个返回Left(List(error1, error2)),但是猫是否提供开箱即用的排序方式来收集所有剩余数据?
我的多项目 sbt 存储库中有 scala 格式插件。
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.3.2")
Run Code Online (Sandbox Code Playgroud)
所以在 sbt 控制台中如果我运行 scalafmt 它工作正常
我的 build.sbt 有:
scalafmtOnCompile := true
Run Code Online (Sandbox Code Playgroud)
如果我在 sbt 中执行 ~compile 或只是手动编译,它不会在编译期间格式化我的代码。
我的设置有什么问题吗?
另外,运行 scalafmt 可以工作,但它不会像我的 Dependency.scala 文件那样格式化 /project 中的 .scala 文件。为什么它忽略这些文件?
我也使用带有金属的 VS Code 作为我的 IDE。
形状列表推断,List[Shape]但盒装形状列表推断List[Box[Square | Circle]]
scala> sealed trait Shape
| case class Square() extends Shape
| case class Circle() extends Shape
| case class Box[+T <: Shape](t: T)
| List(Square(), Circle())
| List(Box(Square()), Box(Circle()))
val res0: List[Shape & Product & Serializable] = List(Square(), Circle())
val res1: List[Box[Square | Circle]] = List(Box(Square()), Box(Circle()))
Run Code Online (Sandbox Code Playgroud)
为什么res0不与List[Square | Circle]对称输入List[Box[Square | Circle]],反之亦然?
Dotty根据联合类型定义最小上限
一组类型的最小上限 (lub) 是这些类型的并集。这取代了Scala 2 规范中最小上限的定义。
与此更改相关的统一规则是什么?
取自typelevel/kind-projector,它们之间的区别是什么:
// partially-applied type named "IntOrA"
type IntOrA[A] = Either[Int, A]
Run Code Online (Sandbox Code Playgroud)
和
// type projection implementing the same type anonymously (without a name).
({type L[A] = Either[Int, A]})#L
Run Code Online (Sandbox Code Playgroud)
?
它们是等价的吗?
当我们尝试从参与者的接收方法中启动多个期货时,我们观察到一种奇怪的行为。如果我们将配置的调度程序用作ExecutionContext,则期货将在同一线程上按顺序运行。如果我们使用ExecutionContext.Implicits.global,则期货将按预期并行运行。
我们将代码简化为以下示例(下面是一个更完整的示例):
implicit val ec = context.getDispatcher
Future{ doWork() } // <-- all running parallel
Future{ doWork() }
Future{ doWork() }
Future{ doWork() }
Future {
Future{ doWork() }
Future{ doWork() } // <-- NOT RUNNING PARALLEL!!! WHY!!!
Future{ doWork() }
Future{ doWork() }
}
Run Code Online (Sandbox Code Playgroud)
一个可编译的示例如下:
import akka.actor.ActorSystem
import scala.concurrent.{ExecutionContext, Future}
object WhyNotParallelExperiment extends App {
val actorSystem = ActorSystem(s"Experimental")
// Futures not started in future: running in parallel
startFutures(runInFuture = false)(actorSystem.dispatcher)
Thread.sleep(5000)
// Futures started in future: running in …Run Code Online (Sandbox Code Playgroud) 当我将包装器定义为值类(扩展AnyVal)时:
class Wrapper(val string: String) extends AnyVal
def wrapperHolder(w: Wrapper): {def wrapper: Wrapper} = new {
def wrapper: Wrapper = w
}
Run Code Online (Sandbox Code Playgroud)
我对于wrapperHolder有以下编译错误:
Error:(5, 22) Result type in structural refinement may not refer to a user-defined value class
def wrapper: Wrapper = w
Run Code Online (Sandbox Code Playgroud)
scala compiler-errors compilation structural-typing value-class
当在密封类型上的模式匹配不够详尽时,Scala会发出警告,但是当密封返回类型时,我们能否检查函数是否返回所有情况?例如,考虑以下ADT
sealed trait Foo
case object Bar extends Foo
case object Qux extends Foo
Run Code Online (Sandbox Code Playgroud)
然后f: Foo => String对代数数据类型起作用Foo
def f(x: Foo): String = x match {
case Bar => "bar"
}
Run Code Online (Sandbox Code Playgroud)
提出警告
match may not be exhaustive.
It would fail on the following input: Qux
def f(x: Foo) = x match {
Run Code Online (Sandbox Code Playgroud)
当返回类型为ADT时,是否可能引发类似的非耗尽警告,例如以下实现f: String => Foo:
def f(x: String): Foo = x match {
case "bar" => Bar
// warn because we never return Qux …Run Code Online (Sandbox Code Playgroud) scala pattern-matching algebraic-data-types non-exhaustive-patterns
我使用依赖异常的Java库。下面的简化代码:
try {
val eventTime = eventTimeString.as[Date]
} catch {
case e: Exception =>
logger.error(s"Can't parse eventTime from $eventTimeString", e)
// take action for the bad Date string.
}
Run Code Online (Sandbox Code Playgroud)
在Java中,我只捕获将字符串解析为Date的异常,就不会捕获其余的异常,因为它们可能是致命的。我的理解是,捕获Exception意味着捕获任何非致命/非严重的异常。既然不一样,那么抓捕Throwable是安全的,但是真的吗?使用此方法的理由是,未知异常可能从更深的堆栈中抛出,如果它们不是致命的,为什么不捕获所有异常。这一直是Java中的问题,在Java中很容易从您进行的直接调用中找到可能的异常,而从更深层的调用中很难找到。这是Scala解决方案的基本含义,是“捕获所有可恢复的异常”?
我的问题是;是上面的代码被认为是良好的Scala风格,是否“安全”,这比仅捕获Date转换为字符串的字符串要好。
我一直习惯于recover在失败的 future 中转换异常,类似于
def selectFromDatabase(id: Long): Future[Entity] = ???
val entity = selectFromDatabase(id) recover {
case e: DatabaseException =>
logger.error("Failed ...", e)
throw new BusinessException("Failed ...", e)
}
Run Code Online (Sandbox Code Playgroud)
此代码片段将 a 转换DatabaseException为BusinessException. 但是,从问题中的评论来看:Scala恢复或recoverWith
...一般来说,“recover”和“recoverWith”的要点不是简单地将异常从一种类型转换为另一种类型,而是通过以不同的方式执行任务来从故障中恢复,以便不再出现故障。
所以显然我不应该使用recover来转换异常。Future转换异常/失败的正确方法是什么Future?
scala ×10
exception ×2
future ×2
akka ×1
casting ×1
compilation ×1
dotty ×1
multiline ×1
sbt ×1
scala-cats ×1
scala-metals ×1
scalafmt ×1
string ×1
subtyping ×1
value-class ×1