Scala - arithmetic operations on params of type Any -


i looking define function takes 2 args of type , attempts add them, this:

def plus(x:any,y:any):try[any] = {    ... } 

yielding success if operands of types can added (arithmetically, not string concat or that), , failure if not. example:

val x:any = 1 val y:any = 2 val z = plus(x,y) // z = success(3) 

or

val x:any = "wrong" val y:any = 2 val z = plus(x,y) // z = failure(...) 

and, have type promotion work addition: int + int => int, int + double => double, etc.

i know there must clever , terse way this, without having check every possible combination of types match. i'm pretty new (only week) scala appreciate suggestions.

in samples know type of arguments @ compile time. in case can better job using type system:

scala> def plus[t: numeric](a: t, b: t) = implicitly[numeric[t]].plus(a, b) plus: [t](a: t, b: t)(implicit evidence$1: numeric[t])t  scala> plus(1, 2) res0: int = 3  scala> plus(1, 2.5) res1: double = 3.5  scala> plus(1, "2") <console>:9: error: not find implicit value evidence parameter of type numeric[any]               plus(1, "2")                   ^ 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -