在 Scala 中输入参数 [英] Type parameter in scala

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

问题描述

我正在尝试理解 Scala 中的类型参数概念.

I am trying to understand the type parameter concepts in scala.

def sum [A] (a:A):A={a}
// used single parameter and its working fine, able to pass any data type.

这里:

def sum[A](a:A,b:A):A={a+b} //declare two arguments

<console>:7: error: type mismatch;
 found   : A
 required: String
 def sum[A](a:A,b:A):A={a+b}

上面的函数有一个类型参数,我没有提到任何数据类型——那怎么把它当作字符串来处理?

The above function has a type parameter, I have not mentioned any data type - then how come it's treated as string?

推荐答案

def sum[A](a:A,b:A):A={a+b}

您正在添加 T + T,编译器无法推断 +T,它会使用默认的implicit +:any2stringadd,所以编译器会抛出required:String错误.

You are adding T + T, the compiler can't infer the + for T, it will use the default implicit +: any2stringadd, so the compiler will throw required: String error.

参见 https://issues.scala-lang.org/browse/SI-8229

  implicit final class any2stringadd[A](private val self: A) extends AnyVal {
    def +(other: String): String = String.valueOf(self) + other
  }

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

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