Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the diff between implicit def and implicit val?

I have the following code, that I can not figure out, what the difference:

  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"
    }  

Both are the implementation for types. The question is, when to use def and when to use val?

The whole code:

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)

}
like image 254
softshipper Avatar asked Mar 15 '19 13:03

softshipper


2 Answers

Your boxPrintable takes a type parameter A and a value argument of type Printable[A], so it must be a def.

String is one specific type, so stringPrintable takes no parameters at all, it's just a constant, so you can define it to be a val.

Nothing more to it.

like image 186
Andrey Tyukin Avatar answered Oct 20 '22 15:10

Andrey Tyukin


def is evaluated on each request.

val is evaluated when the class is created.

In your example you need a def as soon it has parameters, which are not possible with vals.

like image 22
pme Avatar answered Oct 20 '22 15:10

pme