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

时间:2019-03-15 13:32:36

标签: scala scala-cats

我有以下代码,我不知道有什么区别:

  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)

}

2 个答案:

答案 0 :(得分:7)

您的boxPrintable具有类型参数A和类型参数Printable[A]的值参数,因此它必须是def

String是一种特定类型,因此stringPrintable完全不接受任何参数,它只是一个常量,因此您可以将其定义为val

仅此而已。

答案 1 :(得分:3)

每个请求都会评估

def

val在创建类时进行评估。

在您的示例中,您需要一个def,因为它具有参数,而val则不可能。

相关问题