scala – 隐式def和隐式val之间的区别是什么?
发布时间:2020-12-16 18:21:30 所属栏目:安全 来源:网络整理
导读:我有以下代码,我无法弄清楚,有什么区别: implicit def boxPrintable[A](implicit p: Printable[A]) = p.contramap[Box[A]](_.value) implicit val stringPrintable: Printable[String] = new Printable[String] { def format(value: String): String = "Foo
我有以下代码,我无法弄清楚,有什么区别:
implicit def boxPrintable[A](implicit p: Printable[A]) = p.contramap[Box[A]](_.value) implicit val stringPrintable: Printable[String] = new Printable[String] { def format(value: String): String = "Foo " |+| value |+| " Too" } 两者都是类型的实现.问题是,何时使用def以及何时使用val? 整个代码: package com.sweetsoft import cats.instances.string._ import cats.syntax.semigroup._ import cats.Contravariant import cats.Show import cats.instances.string._ final case class Box[A](value: A) trait Printable[A] { self => def format(value: A): String def contramap[B](func: B => A): Printable[B] = new Printable[B] { override def format(value: B): String = self.format(func(value)) } } object Main { val showString = Show[String] implicit def boxPrintable[A](implicit p: Printable[A]) = p.contramap[Box[A]](_.value) implicit val stringPrintable: Printable[String] = new Printable[String] { def format(value: String): String = "Foo " |+| value |+| " Too" } implicit val booleanPrintable: Printable[Boolean] = new Printable[Boolean] { def format(value: Boolean): String = if (value) "yes" else "no" } def main(args: Array[String]): Unit = { println(format("Hello")) //println(format(Box("hello world"))) } def format[A](value: A)(implicit p: Printable[A]): String = p.format(value) } 解决方法
您的boxPrintable采用类型参数A和类型为Printable [A]的值参数,因此它必须是def.
String是一种特定类型,因此stringPrintable根本不接受任何参数,它只是一个常量,因此您可以将其定义为val. 没有更多的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 在bash中检查ssh远程命令的退出状态
- ng命令抛出错误; @ angular-devkit/core似乎不见了
- 如何使用Scalatest在Scala中开发编译器插件
- twitter-bootstrap – 导航栏,引导程序的页眉和页脚,对所有
- angularjs “坑” 小结
- Bootstrap学习系列之使用 Bootstrap Typeahead 组件实现百度
- angular-ui-router – 如何设置强制路由参数
- 在Google Cloud上查看Docker上的Tensorboard
- 尝试从bash中的字符串中检索前5个字符(仅限数字和字母)
- angularjs – 在嵌套指令中传递ng-model