微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala – 隐式def和隐式val之间的区别是什么?

我有以下代码,我无法弄清楚,有什么区别:

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.

没有更多的东西.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐