Scala中的类型推断

Love The Way You Lie 2023-03-05 09:38 38阅读 0赞

Scala类型接口 (Scala Type Interface)

Type interface in Scala is used to make the type declaration optional and handle all type mismatch exceptions if any occurred.

Scala中的Type接口用于使类型声明为可选,并处理所有类型不匹配异常(如果发生)。

This capability of compiler makes it easier for programmers to write code. As the declaration of the data type can be left as compilers work to detect the data type.

编译器的这种功能使程序员更容易编写代码。 由于可以保留数据类型的声明,因此编译器会检测数据类型。

Let’s take an example of a Scala program that declares variables with their data type,

让我们举一个Scala程序的示例,该程序以其数据类型声明变量 ,

  1. object MyClass {
  2. def main(args: Array[String]) {
  3. var data : Double = 34.45;
  4. println("The data is "+ data +" and data type is "+data.getClass);
  5. }
  6. }

Output

输出量

  1. The data is 34.45 and data type is double

Now, let’s see the type inference in action,

现在,让我们看看实际的类型推断,

  1. object MyClass {
  2. def main(args: Array[String]) {
  3. var data = 34.45;
  4. println("The data is "+ data +" and datatype is "+data.getClass);
  5. }
  6. }

Output

输出量

  1. The data is 34.45 and datatype is double

As you can observe, the output of both codes is the same. If the programmer does not provide the data type of the variable the compiler will do the work and give the data a type based on the data that is stored in it.

如您所见,这两个代码的输出是相同的。 如果程序员不提供变量的数据类型,则编译器将进行工作并根据存储在其中的数据为数据提供类型。

函数中的Scala类型推断 (Scala type inference in function)

We have seen the type inference for variables. Now, let’s see type inference in function. In type inference for functions, the return type of functions is omitted also the return keyword is eliminated.

我们已经看到了变量类型推断 。 现在,让我们看看function中类型推断 。 在函数的类型推断中 ,将省略函数的返回类型,并消除return关键字。

Let’s see an example of type inference in function,

让我们看一个函数中类型推断的例子,

  1. object MyClass {
  2. def multiplier(a : Int , b:Int) ={
  3. var product = a*b;
  4. product;
  5. }
  6. def main(args: Array[String]) {
  7. var data = 34.45;
  8. println("The product of numbers is "+ multiplier(34 , 54));
  9. }
  10. }

Output

输出量

  1. The product of numbers is 1836

In the case of type inference, we need to omit the return keyword also. Otherwise, an error is returned by the compiler.

类型推断的情况下,我们还需要省略return关键字。 否则,编译器将返回错误。

翻译自: https://www.includehelp.com/scala/type-inference.aspx

发表评论

表情:
评论列表 (有 0 条评论,38人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java 8改进类型推断

    一 点睛 Java8改进了泛型方法的类型推断能力,类型推断主要有如下两个方面。 可通过调用方法的上下文来推断类型参数的目标类型。 可在方法调用链中,将推断得到的类型参数传

    相关 Scala类型参数

    类型参数是什么?类型参数其实就类似于Java中的泛型。先说说Java中的泛型是什么,比如我们有List a = new ArrayList(),接着a.add(1),没问题,a