Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "::" mean in kotlin?

Tags:

android

kotlin

I'm new to Kotlin
I used this code for opening another activity:

startActivity(Intent(this,IntroAndLang::class.java)) 

current activity and target activity are written in Kotlin

I cant understand why there is not single : instead of :: at IntroAndLang::class.java

like image 919
Winner1 Avatar asked Nov 20 '17 20:11

Winner1


People also ask

What does :: class Java do Kotlin?

By using ::class , you get an instance of KClass. It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc. By using ::class. java , you get an instance of Class.

What does double colon mean in Kotlin?

Kotlin double colon operator The double colon operator (::) is used to create a class or a function reference.

What does .() Mean in Kotlin?

it means that in the lamda you will be passing in, "this" (which is the current object) will be of type T.

What is double exclamation in Kotlin?

AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.


1 Answers

:: converts a Kotlin function into a lambda.

Let's say you have a function that looks like this:

fun printSquare(a: Int) = println(a * 2) 

And you have a class that takes a lambda as a 2nd argument:

class MyClass(var someOtherVar: Any, var printSquare: (Int) -> Unit) {              fun doTheSquare(i: Int) {         printSquare(i)     } } 

How do you pass the printSquare function into MyClass? If you try the following, it wont work:

  MyClass("someObject", printSquare) //printSquare is not a LAMBDA, it's a function so it gives compile error of wrong argument 

So how do we CONVERT printSquare into a lambda so we can pass it around? Use the :: notation.

MyClass("someObject",::printSquare) //now compiler does not complain since it's expecting a lambda and we have indeed converted the `printSquare` FUNCTION into a LAMBDA.  

Also, please note that this is implied... meaning this::printSquare is the same as ::printSquare. So if the printSquare function was in another class, like a Presenter, then you could convert it to lambda like this:

Presenter::printSquare 

UPDATE:

Also this works with constructors. If you want to create the constructor of a class and then convert it to a lambda, it is done like this:

(x, y) -> MyClass::new 

this translates to MyClass(x, y) in Kotlin.

like image 59
j2emanue Avatar answered Sep 23 '22 21:09

j2emanue