Hi, I recently started learning scala and I’m amazed by its cool features
One thing I’m stumbling upon is how implicit works.
I read this cool article on generic programming in scala 3 and tried to implement a utils package to convert a case class to a list of string so I can write it into csv. Basically I just copy and pasted the code in the article, and tried to make it into a package.
Here’s the package I made at src/main/scala/myutils/caseclass2csv.scala
package myutils.caseclass2csv
class CaseClass2CSV:
type Row = List[String]
trait FieldEncoder[A]:
def encodeField(a: A): String
given FieldEncoder[Int] with
def encodeField(x: Int) = x.toString
given FieldEncoder[Boolean] with
def encodeField(x: Boolean) = if x then "true" else "false"
given FieldEncoder[String] with
def encodeField(x: String) = x
trait RowEncoder[A]:
def encodeRow(a: A): Row
given RowEncoder[EmptyTuple] with
def encodeRow(empty: EmptyTuple) =
List.empty
given [H: FieldEncoder, T <: Tuple: RowEncoder]: RowEncoder[H *: T] with
def encodeRow(tuple: H *: T) =
summon[FieldEncoder[H]].encodeField(tuple.head) :: summon[RowEncoder[T]]
.encodeRow(tuple.tail)
def tupleToCsv[X <: Tuple: RowEncoder](tuple: X): List[String] =
summon[RowEncoder[X]].encodeRow(tuple)
This is my main/scala/Main.scala
import myutils.caseclass2csv.CaseClass2CSV
@main def hello: Unit = {
println(CaseClass2CSV().tupleToCsv((42, true, "Hello")))
}
When I run Main.scala
, I get the following error.
<path to my project>/src/main/scala/Main.scala:4:58
no implicit argument of type Nothing was found for an implicit parameter of method tupleToCsv in class CaseClass2CSV
println(CaseClass2CSV().tupleToCsv((42, true, "Hello")))
I guess I’m making a trivial mistake only beginners make, but I could not resolve the issue after several days.
What am I doing wrong here, and how can I fix it?
Also is this the right way to make a package in scala? I come from Python and have less knowledge in Java, so I feel I may have not followed the best practices of making a package (such as, should I separate the traits in a different file, or how to make it possible to import only the function tupleToCsv
, those kind of stuffs).
Thanks in advance!