加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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.

没有更多的东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读