首页 文章

Scala从lambda获得 Value

提问于
浏览
0

我希望从作为参数传递的函数中获取值并返回Option [Int],之后如果我有None抛出异常,并且在任何其他情况下返回值我尝试这样做:

def foo[T](f: T => Option[Int]) = {
   def helper(x: T) = f(x)
   val res = helper _
   res match {
       case None => throw new Exception()
       case Some(z) => z
}

我称之为:

val test = foo[String](myFunction(_))
test("Some string")

我有匹配部分不匹配类型的编译错误(某些[A]传递 - [T] =>需要选项[Int])我理解res变量是对函数的引用,我无法将它与可选的调用get \ gerOrElse相匹配方法 . 此外,我可能只是不知道下划线是如何工作的并且做了一些非常错误的事情,我在这里使用它将一些东西作为参数传递给函数f,你能解释一下我犯了哪个错误吗?

1 回答

  • 2

    helper 是一个采用 T 并返回 Option[Int] 的方法 .

    res 是函数 T => Option[Int] .

    Difference between method and function in Scala

    您无法将函数 T => Option[Int]NoneSome(z) 匹配 .

    你应该有 Option[Int] (例如应用于某些 T 的函数)来进行这样的匹配 .

    可能你想拥有

    def foo[T](f: T => Option[Int]) = {
        def helper(x: T) = f(x)
        val res = helper _
        (t: T) => res(t) match {
          case None => throw new Exception()
          case Some(z) => z
        }
      }
    

    要不就

    def foo[T](f: T => Option[Int]): T => Int = {
        t => f(t) match {
          case None => throw new Exception()
          case Some(z) => z
        }
      }
    

    要么

    def foo[T](f: T => Option[Int]): T => Int = 
        t => f(t).getOrElse(throw new Exception())
    

相关问题