![]() In this Kotlin Tutorial, we learned about Kotlin is Operator, and how to use it to check an object conforms to a given type, with the help of examples. To solve this, specify the type of x as Any, which we did in our previous examples. Happily, Kotlin can infer the generic type from the parameter type so we can omit that when using the constructor: val parameterizedClass ParameterizedClass ( 'string-value' ) val res parameterizedClass.getValue () assertTrue (res is String) Copy. In Kotlin, functional types are represented as generic classes taking different number of parameters: Function0, Function1, Function2.Println("Is x object a String? " + result) Since, Int and String are incompatible types, Kotlin would throw an error. Of course, you can skip this section because in Kotlin, the string interception function subString() calls the Java subString() function. You can go ahead and think of string interception as just a consolidation. You should be familiar with string interception. And in the line 3, we are checking if x is String. If you have a programming background in Java or any other language. Also, no explicit type is specified for x. We have initialized a variable x with integer value. ![]() Kotlin: Incompatible types: String and Int If the type of object is specified or derived implicitly by the value assigned to it, and if this type is not compatible with the type we are checking against, Kotlin would throw the following error. We can also use NOT Operator ! with is as shown in the following program. We can use this expression with is operator as a condition for Kotlin If statement. ![]() Println("Is str object a String? " + result) ![]() In the following program, we will initialize a variable with String, and check programmatically if this variable is of type String, using is operator. It returns true if the object conforms to the given type, or false if not. Any decimal number without mentioning the number type is a double number. Where object is the Kotlin object whose type we would like to check, and Type is the class. Kotlin is Operator is used to check if a an object conforms to a given type.
0 Comments
Leave a Reply. |