1

我正在阅读“学习scalaz”博客系列(这部分:http ://eed3si9n.com/learning-scalaz/a+Yes-No+typeclass.html ),我正在尝试为Option实现truthy类。

这是我想出的类型类,非常简单:

implicit def optionCanTruthy[A: CanTruthy]: CanTruthy[Option[A]] = CanTruthy.truthys({
  case None => false
  case Some(x) => x.truthy
})

这个想法是,如果我们有 A 的类型类,我们可以将上面定义的类型类用于 Option[A] 和 for (x:Option[A]).truthy== true 当且仅当x != None并且x.get.truthy == true

它似乎适用于这样的代码:

1.some.truthy assert_=== true
0.some.truthy assert_=== false
none.truthy assert_=== false

但是当我尝试定义以下方法时:

def truthyIf[A: CanTruthy](cond: A)(ifyes: => String)(ifno: => String): String = {
  if(cond.truthy) { ifyes } else { ifno }
}

cond参数 == None 时它​​会爆炸并出现以下编译错误:

console>:29: error: could not find implicit value for evidence parameter of type CanTruthy[Option[Nothing]]
              truthyIf(none)(y)(n) assert_=== n

任何想法如何解决这个问题,为什么这不起作用?

要使用此代码,您可以克隆此 repo:(git@github.com:tomasherman/scalaz.git此代码位于 src/scala/day1.scala 中)

PS:随意更改问题标题,我不确定“这个问题的名称”是什么

4

1 回答 1

2

我在这里的猜测是,代码无法确定Option它基于仅获得 a的类型None(因此是Option[Nothing])。尝试输入您的None第一个,以便您调用的代码在将其传递给truthyIf. 如果是 a String,那么我的建议是这样声明:

val opt:Option[String] = None

一旦您的代码可以识别底层类型,我猜它会停止抱怨。

于 2013-07-11T12:20:34.837 回答