Scala中的类型推断

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程序的示例,该程序以其数据类型声明变量

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

Output

输出量

The data is 34.45 and data type is double

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

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

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

Output

输出量

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,

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

object MyClass {
    def multiplier(a : Int , b:Int) ={
        var product = a*b; 
        product;
    }
    def main(args: Array[String]) {
        var data  = 34.45;
        println("The product of numbers is "+ multiplier(34 , 54));
    }
}

Output

输出量

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值