隐式def和隐式val之间的差异是什么?

问题描述 投票:4回答:2

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

  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)

}
scala scala-cats
2个回答
8
投票

你的boxPrintable采用类型参数APrintable[A]类型的值参数,因此它必须是def

String是一种特定的类型,所以stringPrintable根本没有参数,它只是一个常数,所以你可以将它定义为val

没有更多的东西。


3
投票

def根据每个请求进行评估。

在创建类时评估val

在你的例子中,你需要一个def,因为它有参数,这是vals无法实现的。

© www.soinside.com 2019 - 2024. All rights reserved.