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智能型铸造 (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 = objprintln("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.

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

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 hereMyJava 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 truefun 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: Vehicleval 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方法类型

kotlin方法类型_Kotlin类型检查,Kotlin类型铸造相关推荐

  1. java kotlin相互调用_Kotlin的互操作——Kotlin与Java互相调用

    原标题:Kotlin的互操作--Kotlin与Java互相调用 互操作就是在Kotlin中可以调用其他编程语言的接口,只要它们开放了接口,Kotlin就可以调用其成员属性和成员方法,这是其他编程语言所 ...

  2. python类型提示包 检查静态类型_Pyright:微软提供的Python静态类型检查器

    ​ 改进您的编程技术和方法,成为一个更有生产力和创造性的Python程序员.本书探索了一些概念和特性,这些概念和特性不仅将改进您的代码,而且还将帮助您理解Python社区,并对Python哲学有深入的 ...

  3. Kotlin实战指南六:可空类型、非可空类型

    转载请标明出处:https://blog.csdn.net/zhaoyanjun6/article/details/87877529 本文出自[赵彦军的博客] 可空类型.非可空类型 变量可空类型 方法 ...

  4. 【Kotlin基础系列】第4章 类型

    1 基本类型 在 Kotlin 中,所有东西都是对象,在这个意义上讲我们可以在任何变量上调用成员函数与属性. 一些类型可以有特殊的内部表示--例如,数字.字符以及布尔可以在运行时表示为原生类型值,但是 ...

  5. 《疯狂Kotlin讲义》读书笔记2——Kotlin的基本类型

    Kotlin的基本类型 和Java一样,Kotlin也是一种强类型语言,即要求: 1.所有变量都需要先声明.后使用. 2.指定类型的变量只能接受类型与之匹配的值. 强类型语言可以在编译过程中发现源代码 ...

  6. Kotlin入门-万物皆对象,基础类型

    Kotlin说:万物皆对象. 可以说,Kotlin全面的接管了所有类型.一统天下. 即是基础,那就需要,通盘了解.按目录来就行.也有Xmind版本 github地址 本文将从下面几个方面去讲解 数字 ...

  7. Go 学习笔记(35)— Go 接口 interface (接口声明、接口初始化、接口方法调用、接口运算、类型断言、类型查询、空接口)

    1. 接口概念 接口是双方约定的一种合作协议.接口实现者不需要关心接口会被怎样使用,调用者也不需要关心接口的实现细节.接口是一种类型,也是一种抽象结构,不会暴露所含数据的格式.类型及结构. 接口内部存 ...

  8. 苹果新的编程语言 Swift 语言进阶(十三)--类型检查与类型嵌套

    一 类型检查 1. 类型检查操作符 类型检查用来检查或转换一个实例的类型到另外的类型的一种方式. 在Swift中,类型检查使用is和as操作符来实现. is操作符用来检查一个实例是否是某种特定类型,如 ...

  9. Java 8 - 04 类型检查、类型推断以及限制

    文章目录 Pre 类型检查 同样的 Lambda,不同的函数式接口 菱形运算符 特殊的void兼容规则 类型推断 使用局部变量 Pre 当我们第一次提到Lambda表达式时,说它可以为函数式接口生成一 ...

最新文章

  1. 万字长文爆肝Python基础入门【巨详细,一学就会】
  2. C++ Primer 5th笔记(chap 16 模板和泛型编程)函数模板显式实参
  3. leveldb 学习记录(四)Log文件
  4. Java程序员从笨鸟到菜鸟之(九十九)深入java虚拟机(八)开发自己的类加载器...
  5. SVN或其他网盘类软件同步图标不显示的异常
  6. MIT陈刚教授案件新进展,律师反诉美检察官利用不实信息制造舆情、干扰司法公正...
  7. 问题 E: Search Problem (II)
  8. MacBook进阶技巧,如何在触控栏添加一键截屏?
  9. idirect3ddevice9虚函数偏移_C++ 虚函数简介
  10. linux运行h3c校园网,H3C Lite轻量级校园网认证Linux客户端(For SHNU)
  11. CentOS Linux操作系统
  12. 平方米的计算机公式,表格中平方米计算公式(怎么用excel计算平方)
  13. 数字逻辑——七段数码管
  14. C语言中的取绝对值函数
  15. 收不到手机验证码怎么办
  16. 【SDOI2009】【BZOJ1227】虔诚的墓主人
  17. 又一个美食账号火了,3个月涨粉200万,快手乡土账号有何魔力?
  18. DNS服务之智能DNS
  19. uni-app中Card slots的使用(添加点击事件)(uni-card)
  20. 解决PS中:无法将图片存储为Web存储格式,及如何将图片大小修改成10KB的问题

热门文章

  1. WPF DataGrid 样式分享
  2. [转载] Python 列表(List)
  3. Vue.js 学习笔记 二,一些输出指令
  4. Ngnix中的fastcgi參数性能优化和解释
  5. 浅谈es6 promise
  6. Eclipse 常用快捷键和使用技巧
  7. Mongodb在Ubuntu下的安装
  8. iframe加载完成后操作contentDocument
  9. deeplab v3+---Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation
  10. 【ROS学习笔记】(五)话题消息的定义与使用