4

I would like to generate functions for a class accepting 1 type parameter

case class C[T] (t: T)

depending on the T type parameter.

The functions I would like to generate are derived by the functions available on T.

What I would like exactly, is to make all the functions available for T, also available for C.

As an example for C[Int], I would like to be able to call on C any function available on Int and dispatch the function call to the Int contained in C.

val c1 = new C(1)
assert(c1 + 1 == 2)

How can I achieve this by using Scala 2 or dotty macros? Or, can this be achieved in another way?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
user2468425
  • 419
  • 2
  • 13
  • Possibly similar question to https://stackoverflow.com/questions/55826206/way-to-enhance-a-class-with-function-delegation/ – Mario Galic Jul 06 '19 at 16:01
  • 2
    @MarioGalic in that question a class is monomorhic, here it's polymorhic, this makes a difference. `export` seems not to work now. – Dmytro Mitin Jul 06 '19 at 16:09

1 Answers1

3

What you're trying to do is easily achievable with implicit conversions, so you don't really need macros:

case class C[T] (t: T)

object C { //we define implicit conversion in companion object
  implicit def conversion[T](c: C[T]): T = c.t
}

import scala.language.implicitConversions
import C._

val c1 = C(1)
assert(c1 + 1 == 2) //ok

val c2 = C(false)
assert(!c2 && true) //ok

Using implicit conversions means, that whenever compiler would notice, that types don't match, it would try to implicitly convert value applying implicit function.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
  • 1
    thanks, this is definitely a right answer to my question I would really appreciate you giving a try at a similar but more complex one I just posted: https://stackoverflow.com/questions/56916413/generate-functions-based-on-type-parameter – user2468425 Jul 06 '19 at 17:53