在 Scala 中添加泛型类型参数 [英] Addition with generic type parameter in Scala

查看:40
本文介绍了在 Scala 中添加泛型类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 的新手,并尝试使用泛型类型参数编写加法程序,如下所示

Hi I am new to scala and trying to write addition program in with generic type parameter as shown below

object GenericTest extends Application {
  def func1[A](x:A,y:A) :A = x+y    
    println(func1(3,4))
}

但这不起作用.我犯了什么错误.

But this does not work .What mistake i am making .

推荐答案

A 在这种情况下可以是任何类型.x + y 表示 x.+(y),它只会在以下情况下编译 a) A 类型有一个方法 +,或 b) 类型 A 可以隐式转换为具有方法 + 的类型.

A could be any type in this case. x + y means x.+(y), which would only compile if either a) the type A had a method +, or b) the type A was implicitly convertible to a type with a method +.

scala.Numeric 类型提供了编写抽象数字系统的代码的能力——它可以用 Double、Int 甚至你自己的奇异数字系统调用,例如复数.

The type scala.Numeric provides the ability to write code that abstracts over the numeric system -- it could be called with Double, Int, or even your own exotic numeric system, such as complex numbers.

您可以向 Numeric[A] 类型的方法添加隐式参数.

You can add an implicit parameter to your method of type Numeric[A].

object GenericTest extends Application {
  def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y    
}

在 Scala 2.8 中,这可以缩短:

In Scala 2.8, this can be shortened:

object GenericTest extends Application {
  def func1[A: Numeric](x: A, y: A): A = x + y    
}

这篇关于在 Scala 中添加泛型类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆