Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

android - what does "::" mean in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

:: 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 an object and then convert it to a lambda, it is done like this:

(x, y) -> MyObject::new

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...