Question about class types

I need to define a class of type Field as follows:

 trait Field[A] { // Additive identity def zero: A // Multiplicative identity def one: A } 

A class of type Numeric also provides zero and one methods.

I want every class that a Numeric instance is available to use wherever a class with a Field instance is required. For example, the following should work:

 def func[F: Field](f: F) = println(f) func(2) 

Could you suggest how to do this? I tried the following, but this did not work:

 scala> implicit def numericToField[N](n: Numeric[N]) = new Field[N] { | def zero = n.zero | def one = n.one | } numericToField: [N](n: Numeric[N])java.lang.Object with Field[N] scala> def func[F: Field](f: F) = println(f) func: [F](f: F)(implicit evidence$1: Field[F])Unit scala> func(2) <console>:12: error: could not find implicit value for evidence parameter of type Field[Int] func(2) ^ 
+4
source share
2 answers

You almost got it. You just need to make this small change:

 scala> implicit def numericToField[N](implicit n: Numeric[N]) = new Field[N] { | def zero = n.zero | def one = n.one | } 
+7
source

Your solution is very correct, but you must define the function like this:

 def func[F <% Field](f:F) = println(f) 

As you have defined it now, F should be a field (or a subtype of a field), and not just be convertible to one. The designation "F <% Field" means that all values ​​that have implicit conversion to fields are also valid. The second solution would also work if you created an implicit Field [Int] instance somewhere in the area from the func (2) function call.

+3
source

Source: https://habr.com/ru/post/1338090/


All Articles