Generics in scala for addition -


class calculator[a:numeric]{    var x:a = _;    def sum() : = x+x;  //error:   } 

compiler errors:

  1. can't resolve + symbol on a
  2. type mismatch; expected: string, actual: a

class calculator[a: numeric]{ ... } 

is syntax sugar for

class calculator[a](implicit n: numeric[a]){ ... } 

if in the docs numeric you'll find implicit def mkorderingops uses "enrich library" pattern add math operators + a type.

you need import mkorderingops instance of numeric.

keeping current class signature, can use implicitly[numeric[a]] instance. putting together, get:

class calculator[a: numeric] {   private val n = implicitly[numeric[a]]   import n._ // mkorderingops included here        var a: = _   def sum = + // + coming mkorderingops conversion } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -