kotlin方法类型_Kotlin类型检查,Kotlin类型铸造

kotlin方法类型

Today we will look into Kotlin type checking and smart type casting. We will use Kotlin Online playground for code snippets.

今天,我们将研究Kotlin类型检查和智能类型转换。 我们将使用Kotlin在线游乐场编写代码段。

Kotlin类型检查 (Kotlin Type Checking)

Type Checking is the way to check the type of a data at runtime. In Java, we have the instanceof keyword to check the type. Kotlin uses is and !is keywords to check whether a property is and is not of a certain type respectively.

类型检查是在运行时检查数据类型的方法。 在Java中,我们有instanceof关键字来检查类型。 Kotlin使用is!is关键字检查属性是否分别某种类型的不是

Let’s look at an example code for the same.

让我们看一个相同的示例代码。

var myProperty = "xyz"
var otherProperty = 1
if(myProperty is String)
{
    println("type is String")
}
else{
    println("unknown type")
}

if(otherProperty !is Double)
{
    println("not a string")
}
else{
    println("unknown type")
}

The first if-else expression would print type is String. The second would give a compilation error since Kotlin is powerful enough to determine the types at compile time itself.

第一个if-else表达式将打印类型为String。 第二个将给出编译错误,因为Kotlin足够强大,可以在编译时自行确定类型。

Let’s create a list of Any objects and check the type of each element.

让我们创建一个Any对象的列表,并检查每个元素的类型。

We’ll use the when statement to check the type of each element in a for loop.

我们将使用when语句来检查for循环中每个元素的类型。

val anyList: List<Any> = listOf("JournalDev.com", "Java", 101, 12.5f,12.5456789,false)

    for(value in anyList) {
        when (value) {
            is String -> println("String: '$value'. Capitalize :${value.capitalize()}")
            is Int -> println("Integer: '$value'")
            is Double -> println("Double: '$value'")
            is Float -> println("Float: '$value'")
            else -> println("Unknown Type")
        }
    }

Following is the output of the above code.

kotlin type checking

以下是上述代码的输出。

Kotlin智能型铸造 (Kotlin Smart Type Casting)

Smart type casting is one of the most interesting features available in Kotlin. It automatically casts a property to the desired type on the right hand side if the condition meets.

智能类型转换是Kotlin中最有趣的功能之一。 如果条件满足,它将在右侧自动将属性强制转换为所需的类型。

fun getName(obj: Any?) {
        if (obj == null || obj !is String) {
            return
        }
        val string = obj
        println("Length of the string is ${string.length}")
    }

    getName(null)
    getName("Anupam")

In the above code, we don’t need to unwrap the optional. If the smart cast passes the above null checker, optional is unwrapped automatically.

在上面的代码中,我们不需要打开可选的包装。 如果智能强制转换通过了上述空检查器,则将自动解开Optional选项。

The output printed from the above piece of code is given below.

kotlin smart type casting

下面给出了以上代码输出的输出。

The same equivalent code in Java would look like this:

Java中相同的等效代码如下所示:

class MyJava
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
 
	MyJava mj = new MyJava();
	mj.printStringLength("Anu");
 
	}
 
	public void printStringLength(Object obj) {
        if (obj instanceof String) {
        String str = (String) obj;
        System.out.print("String substring is ");
        System.out.print(str.substring(1));
 
      }
    }
}

In the above code, we’re first checking the instanceOf and then explicitly type casting. Kotlin makes it way simpler thanks to Smart Casting.

在上面的代码中,我们首先检查instanceOf ,然后显式键入强制类型转换。 借助Smart Casting,Kotlin使其变得更加简单。

二元运算符的智能转换 (Smart Casting With Binary Operators)

Smart Casting is also possible with binary operators as shown in the below code.

如以下代码所示,使用二进制运算符也可以进行智能转换。

fun newStringOnlyIfLength6(str: Any): Boolean {
        return str is String && str.length == 6
}

print(newStringOnlyIfLength6("Kotlin")) //prints true


fun stringOnlyIfLength6(str: Any): Boolean {
        return str !is String || str.length == 6
}

print(stringOnlyIfLength6("Kotlin")) //prints true

In the above code, in the first function, if the first condition is true, Kotlin type casts the parameter in the second parameter to the same type.

在上面的代码中,在第一个函数中,如果第一个条件为true,则Kotlin类型会将第二个参数中的参数强制转换为相同类型。

班上的聪明演员 (Smart Casts in Classes)

Let’s create classes that implement an interface as shown below:

让我们创建实现接口的类,如下所示:

import java.util.*

fun main(args: Array<String>) {
    class Car : Vehicle {
        override fun printDetails() {
            println("AUDI Rocks")
        }
    }
    class Bike : Vehicle {
        override fun printDetails() {
            println("Bullet fires")
        }
    }
    val printMe: Vehicle
    val random = Random()

    fun rand(from: Int, to: Int): Int {
        return random.nextInt(to - from) + from
    }
    printMe = if (rand(0, 10) % 2 == 0) {
        Car()
    } else {
        Bike()
    }
    if (printMe is Car) {
        printMe.printDetails()
    }
    if (printMe is Bike) {
        printMe.printDetails()
    }
}

interface Vehicle {
    fun printDetails()
}

The Random function gets a random integer between 0 to 10. Based on whether it’s even or odd, the interface creates instantiates from either of the classes.

Random函数获取一个介于0到10之间的随机整数。基于它是偶数还是奇数,接口从任何一个类创建实例化。

The is operator then calls the method in the if expressions by smart casting the type of the class.

然后, is运算符通过智能转换类的类型在if表达式中调用该方法。

Note: The Kotlin compiler does not smart cast when it cannot guarantee that the value hasn’t changed between check and usage. It always smart casts for val properties and can never do so for var properties.

注意:当Kotlin编译器不能保证在检查和使用之间该值未发生变化时,它不会智能强制转换。 它始终对val属性进行智能转换,而永远不会对var属性进行转换。

显式铸造 (Explicit Type Casting)

We can explicitly type cast properties in Kotlin using the as operator.

我们可以使用as运算符在Kotlin中显式键入类型属性。

val object: Any = "Hello World"
val str: String = object as String
println(str.length)

The as operator is unsafe. It can lead to ClassCastException similar to Java in scenarios shown below.

as运算符不安全。 在下面显示的方案中,它可能导致类似于Java的ClassCastException

var y = null
var x = y as String
println(x) // crashes

x is not a nullable type, so it cannot be set to null. For this case, we’ll can do either of the following:

x不是可为null的类型,因此不能将其设置为null。 对于这种情况,我们可以执行以下任一操作:

var y = null
var x = y as String?
println(x)

This allows us to set x as a null.

这使我们可以将x设置为null。

But the above approach would fail when:

但是上述方法在以下情况下将失败:

var y = 5
var x = y as String?
println(x) //crashes

So we need to use the as? operator which instead of giving a runtime exception, sets a null value if the cast doesn’t succeed.

那么我们需要使用as? 如果强制转换不成功,该运算符将设置为null值,而不是给出运行时异常。

var y = 5
var x = y as? String
println(x) //gives a null

That’s all for type checking and smart casting in kotlin programming language.

这就是用Kotlin编程语言进行类型检查和智能转换的全部内容。

翻译自: https://www.journaldev.com/19684/kotlin-type-checking-kotlin-type-casting

kotlin方法类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值