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)
}
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.
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 val
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With