gpt4 book ai didi

Scala Right, Left 分解困难

转载 作者:行者123 更新时间:2023-12-02 06:26:51 25 4
gpt4 key购买 nike

我做了一些 scala 练习。我有一个方法:

def getDepartment: (Either[String, Employee]) => Either[String, String] = ???

我需要工具主体。方法参数数据示例:

  1. 右(员工(“乔”,“财务”,一些(“朱莉”)))
  2. 右(员工(“玛丽”,“IT”,无))
  3. Left("找不到员工")

方法接下来应该返回:

  1. 右(“财务”)
  2. 右("IT")
  3. Left("找不到员工")

所以我要添加正文:

def getDepartment: (Either[String, Employee]) => Either[String, String] = _ match {
case _: Left[String, Employee] =>
println(s"Left: " + _)
_ // unbound placeholder parameter - compilation error
case _: Right[String, Employee] =>
println(s"Right: " + _)
_ // unbound placeholder parameter - compilation error
case _ =>
println(s" " + _)
_ // unbound placeholder parameter - compilation error
}

我知道我的实现是不正确的,因为一直存在编译错误。看来我没有实现所需解决方案的经验。

关于方法声明,我发现信息是scala tutorial .但是我没有任何有用的想法如何将 _ 映射到所需的类型。可能有人可以帮助修复我的编译错误,为主体实现提出更好的方法。

附言

解决方案应在Optional 上实现,无需错误处理。

附言2

任务取自 online resource .练习 4.6 中的第一个任务。

最佳答案

  1. 前两种情况需要给匹配的值命名,第三种没有用(技术上讲,如果参数为null,它可以匹配,但那是调用方的错误,让他们处理):

    def getDepartment: (Either[String, Employee]) => Either[String, String] = _ match {
    case left: Left[String, Employee] =>
    println(s"Left: " + left)
    ???
    case right: Right[String, Employee] =>
    println(s"Right: " + right)
    ???
    }

    请注意,两个 ??? 都需要替换为类型为 Either[String, String] 并使用 left/正确

  2. 但是最好使用提取器来匹配LeftRight:

    def getDepartment: (Either[String, Employee]) => Either[String, String] = _ match {
    case Left(string) =>
    ??? // use string ("contents" of the Left) here
    case Right(employee) =>
    ??? // use employee here
    }
  3. _ match { ... } 形式的函数有一个特例,它允许您简单地编写

    def getDepartment: (Either[String, Employee]) => Either[String, String] = {
    case Left(string) =>
    ??? // use string ("contents" of the Left) here
    case Right(employee) =>
    ??? // use employee here
    }

关于Scala Right, Left 分解困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com