【问题标题】:How should I get B form A => B我应该如何从 A => B 中获得 B
【发布时间】:2021-04-22 14:49:35
【问题描述】:

我是 Scala 新手,遇到了这种奇怪的情况。

def bar[A, B](implicit foo: A => B): B = {
  // do something
  foo
}

然后我得到了类似的错误

require B but found A => B

我应该如何从 A 中得到 B => B

这就是我这样做的原因,我有两个功能:

def funcA: String = {
  def getStrA: String = "A"

  // then there's the same operation in both functions
  Try{  } match {
    case Success(_) => getStrA
    case Failure(_) => // exactlly same error handler in both function
  }
  
}
def funcB: Int = {
  def doSomething(x: Int): Int = {
    // do something
    x / 1
  }
  
  val x = 1
  Try{  } match {
    case Success(_) => doSomething(1)
    case Failure(_) => // exactlly same error handler in both function
  }
}

这就是我想要实现的目标

def funcA: String = {
  implicit def getStrA: String = "A"

  bar  
}
def funcB: Int = {
  val x = 1
  implicit def doSomething(x: Int): Int = {
    // do something
    x / 1
  }
  
  bar
}

def bar[A, B](implicit foo: A => B): B = {
  Try{  } match {
    case Success(_) => foo
    case Failure(_) => // exactlly same error handler in both function
  }
}

【问题讨论】:

  • 调用foo() 传递A 类型的值。
  • 那我应该怎么称呼这个bar函数
  • This 可能对你有帮助

标签: scala functional-programming


【解决方案1】:

您有一个从AB 的转换。您需要返回B。这样做的唯一方法是将A 传递给函数。这个签名暗示你有一些有效的A 值(很可能是硬编码的),你会一直在这里使用。

def bar[A, B](implicit foo: A => B): B = {
  val a: A = ... // hmm...
  foo(a)
}

考虑到A 是参数化的,那么您要么缺少某些信息,要么无法创建此A(它不能是null,因为并非所有类型都可以将null 作为值),所以在这种情况下你可能需要抛出异常。可能您缺少一些 A 提供程序,或者您应该始终失败此操作。

更新:

在您的代码中根本不需要使用隐式:

def bar[B](f: onSuccess: A => B) = 
  Try{ some operations } match {
    case Success(value) => onSuccess(value)
    case Failure(_)     => // error handler 
  }

def funcA = bar(_ => "A")
def funcB = bar(_ => 1)

【讨论】:

  • 你的意思是我应该把这个a传递给bar函数?
  • 如果你能找出A,那么是的,如果你不能,那么你就不能创建B
  • 但是我仍然需要 A 参数化,并且我不想将这个 A 明确传递给 bar。我该怎么做呢。
  • 1)。将A 作为隐式传递。 2)。这是非常过度设计的反模式,因为您的代码中不需要隐式。使用高阶函数可以更清晰地实现一切。
  • 我用一个例子发布了更新。如果仍然无法帮助您,请使用原始代码的工作示例以及所有签名创建一个 Scastie。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2013-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多