还在使用Java开发Android应用吗? 尝试使用Kotlin。

Kotlin has been a huge breakthrough for the last 2 years, it has been a trending topic everywhere and its popularity is still rising. And it is also official that Google has pushed Kotlin to become the official language for Android App Development.

在过去的两年中,Kotlin取得了巨大的突破,在各个地方都成为热门话题,并且其受欢迎程度仍在上升。 Google推动Kotlin成为Android App Development的官方语言也是官方的。

But even then, a lot of people still prefer Java over Kotlin for Android development, why is that? One of the main reason for that is people are still not comfortable in changing their main language of choice from Java to Kotlin, people are afraid of changing into new things.

但是即使那样,在Android开发中,仍然有很多人还是喜欢Java而不是Kotlin,为什么呢? 造成这种情况的主要原因之一是,人们仍然不习惯将其主要的选择语言从Java更改为Kotlin,人们害怕更改为新事物。

立即开始使用Kotlin,简单的方法 (Start Using Kotlin now, the easy way)

In actuality, it is very easy to switch into Kotlin from Java, being a very flexible language, you can easily code Kotlin but idiomatically, it's Java!

实际上,从Java切换到Kotlin非常容易,这是一种非常灵活的语言,您可以轻松地编写Kotlin的代码,但习惯上是Java!

So now, here are several things to be noted on when switching to Kotlin from Java:

因此,现在,从Java切换到Kotlin时需要注意以下几点:

1. Java InteroperabilityKotlin is fully interoperable with Java and also, the other way around. What does that mean, it means that your Kotlin can call your Java code, it makes things very easy for app migration, you already code halfway with Java? Doesn't matter, code Kotlin anyway.

1. Java互操作性 Kotlin与Java完全互操作,反之亦然。 这是什么意思,这意味着您的Kotlin可以调用您的Java代码,这使应用程序迁移变得非常容易,而您已经使用Java进行了一半编程? 没关系,还是用Kotlin编码。

2. No more primitive data typesRemember when choosing either using int or Int in java takes you half a day? There is no more primitive data types now in Kotlin, everything has been wrapped in Object instead.

2.没有更多原始数据类型还记得在Java中选择使用intInt时需要花费半天的时间吗? 现在Kotlin中不再有原始数据类型,所有内容都包装在Object中。

3. Slightly changed syntax (But don't worry it's easy to catch up)Several syntax like variable, function and class declaration has been slightly changed, but if you come from OOP background such as Java, it will not be such an issue. And also, void keyword and semi-colon (';') have been removed, thanks Kotlin for that semicolon removal!!I will present you with the basic examples with Android class:

3.语法稍有更改(但不要担心,这很容易赶上)变量,函数和类声明之类的几种语法已稍作更改,但是如果您来自Java之类的OOP背景,就不会有这样的问题。 并且,void关键字和分号(';')也已删除,感谢Kotlin的分号删除!!我将为您介绍Android类的基本示例:

//Inheritance and implementation is using ':' now
class BasicActivity : AppCompatActivity() {
    //variables declaration is now variable name first then type
    var a :Int = 10 //var is for mutable
    val b :Int = 15 //val is for immutable

    /*lateinit keyword must be added for initialisation of non-
    primitive type without initial value in Kotlin*/
    lateinit var someTextView:TextView

    //Also, no more new keyword here
    var gameList:List<Integer> = ArrayList()

    //overriding is using keyword instead of 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_basic)
    }
}

4. Type inferenceKotlin will make life easier by providing type inference for variables:

4. 类型推断 Kotlin将通过为变量提供类型推断来简化生活:

var a = 5 //will automatically infer this as integer
var b = "John" // will automatically infer this as String

5. Null safety checksKotlin has provided null safety checking in order to avoid null pointer exception. Every variable that might return null value will be marked (and must be marked) with ?  sign.

5. 空安全检查 Kotlin提供了空安全检查,以避免空指针异常。 每个可能返回空值的变量都将被标记(并且必须被标记) ? 标志。

var a:String? = null
var b:String = null //not allowed

It also provides null safety call in order to avoid Null-Pointer Exception (Java Billon Dollar Mistakes)

它还提供了空安全调用,以避免出现空指针异常(Java Billon Dollar错误)。

//not allowed, a might be null
a.function() 

// this will not throw null pointer, instead will continue the flow
a?.function()

//force function call, can cause NPE, use this only if 100% sure that this value will not be null
a!!.function()

6. No more static keywordStatic keyword has now been replaced with Object keyword, both for classes and methods, more specifically Companion Object for methods.7. Switch case modifiedSwitch case has now been modified into a new keyword, called when. Which looks cleaner and more flexible:

6. 不再有static关键字 Static关键字现在已被Object关键字替换,用于类和方法,更具体地说是Companion Object的method.7。 修改了开关案例现在已经将开关案例修改为一个新关键字,称为when 。 看起来更干净,更灵活:

when (x) {
    1 -> println("One")
    2 -> print("Two")
	else -> print("Others")
}

8. No more checked exceptionRemember when you were making some operations or casting in Java, and that red warning comes out and told you to add exception checking there? It has been removed now in Kotlin. Now, your IDE will not force you to do any exception anymore!!

8. 没有更多的检查异常还记得您在Java中进行某些操作或强制转换时,红色警告发出并告诉您在此处添加异常检查吗? 现在已在Kotlin中将其删除。 现在,您的IDE将不再迫使您执行任何异常!

That's all for the part which you need to start developing in Kotlin, but idiomatically Java.It's not hard to get into Kotlin now, right? Now Kotlin doesn't seem that different from Java.

这就是您开始在Kotlin中进行开发所需的全部内容,但是对于Java来说却是惯用的。现在进入Kotlin并不难,对吧? 现在Kotlin似乎与Java没有什么不同。



Kotlin提供的功能 (Features Provided By Kotlin)

Now, after taking a look at how Kotlin and Java differ, we also need to take a look at the features provided by Kotlin and how to slowly start doing Kotlin, the Kotlin way:

现在,在了解Kotlin和Java的不同之处之后,我们还需要了解Kotlin提供的功能以及如何以Kotlin的方式缓慢地开始做Kotlin:

1. Flexibility One of the main reasons for my love in Kotlin is the flexibility of the language. Are you OOP purist? Are you itching to try Functional Programming which currently is the hot topic around? And for the love of coding god, you can do both in Kotlin! Despite not fully providing all the features FP provides, it is good enough to support it.

1.灵活性我喜欢Kotlin的主要原因之一是语言的灵活性。 您是OOP的纯粹主义者吗? 您是否想尝试使用功能编程 (当前是热门话题)? 为了热爱编码上帝,您可以在Kotlin中做到这两者! 尽管没有完全提供FP提供的所有功能,但足以支持它。

2. Lambda SupportYes, I know that now Java 8 supports lambda, but Kotlin came first at this and it does a very good job in that. Sure, transitioning into using Lambda Function will be difficult at first, but as stated, Kotlin is really flexible on that. So hey, it's your call!Some of the Android library has also enabled Lambda support, for instance View.OnClickListener (If you came from Android Background, I'm certain that this method is already very familiar to you) :

2. Lambda支持是的,我知道Java 8现在支持lambda,但是Kotlin在这方面排在首位,并且在这方面做得很好。 当然,一开始很难过渡到使用Lambda函数,但是如上所述,Kotlin确实很灵活。 嘿,这是您的电话!某些Android库也启用了Lambda支持,例如View.OnClickListener (如果您来自Android Background,我肯定您已经非常熟悉此方法了):

val randomButton : Button

//using lambda function as argument
randomButton.setOnClickListener{v -> doRandomStuff(v) }

3. Data ClassKotlin has provided a substitute for Model/Entity class, called Data class. It removes the need for redundant setter getter and also has in-built equal method and toString function without you having to make one for it. It's also very easy to utilize:

3. 数据类 Kotlin提供了Model / Entity类的替代品,称为Data类。 它消除了对多余的setter getter的需求,并且具有内置的equal方法和toString函数,而无需为此做一个。 它也很容易使用:

data class Person(
    val id:String,
    val name:String = "John Doe" //Default Value
)

//Initialisation block
var person = Person("id","Not John")

4. Extension FunctionsKotlin allows the usage of extension functions, which makes code more readable. Also, it will enable you to give functionality to a class without modifying the class itself:

4. 扩展功能 Kotlin允许使用扩展功能,这使代码更具可读性。 此外,它还使您能够为类提供功能,而无需修改类本身:

fun Int.superOperation(anotherInt:Int):Int {
    val superNumber = this * anotherInt + anotherInt
    return superNumber
}

//you can now call the functions
val someNumber = 5
val superNumber = someNumber.superOperation(10) //65

5. Named and Default ArgumentsLike C#, Kotlin also supports named and default parameters for its methods. It completely removes the need to pass values in each arguments. You can select which value you want to modify, and voila! No more hassles in passing the same particular value for 10 of your function calls!

5. 命名和默认参数与C#一样,Kotlin也支持其方法的命名和默认参数。 它完全消除了在每个参数中传递值的需要。 您可以选择要修改的值,瞧! 不再为10个函数调用传递相同的特定值而烦恼!

//variable declaration
fun someOperations(var x: Int, var y:Int, var z:Int = 1){
	return x+y+z
}

someOperations(1,2) //return 4
someOpeartions(y = 1, x = 1) //return 3

6. Referential EqualityKotlin also comes with referential equality ('==='), it will check if two variables are currently referring to the same Object.

6. 引用相等 Kotlin还带有引用相等('==='),它将检查当前是否有两个变量引用同一对象。

var a = 10
var b = 10
a == b //true
a === b //true also, primitive type object equation will only check its value

data class Person (val name: String)

val p1 = Person("John")
val p2 = Person("John")

p1 == p2 //true
p1 === p2 //false

7. Smart castingInstead of using instance of, Kotlin now provides easier and more readable syntax to use for casting or type checking:

7. 智能转换 Kotlin现在不再使用的实例,而是提供了更简单,更易读的语法来进行转换或类型检查:

//type checking
//kotlin smart cast mechanism will also automatically change the object into corresponding type if it passes the type checking
if (shape is Circle) {
    println(“it’s a Circle”)
    shape.radius //automatically be casted as Circle
} else if (shapeObject is Square) {
    println(“it’s a Square”)
} else if (shapeObject is Rectangle) {
    print(“it’s a Rectangle”)
}

Kotlin also has as keyword to enable explicit casting:

Kotlin还具有as关键字来启用显式转换:

//It's considered unsafe since it behaves simillarly like static casting
var anotherShape = shape as Circle

//This can be used instead for safe casting
var safeShape = shape as? Circle

8. CoroutinesAsynchronous call has always been a hassle in Java. Making Thread takes so much of the code space and makes the code unreadable. Coroutines has been made to replace traditional thread operation, granting a clean and robust code:

8. 协程异步调用在Java中一直是一个麻烦。 使用Thread会占用大量代码空间,并使代码无法读取。 协程已取代传统的线程操作,并提供了干净,健壮的代码:

import kotlinx.coroutines.*

fun main() {
    // launch a new coroutine in background and continue
    GlobalScope.launch { 
        // non-blocking delay for 1 second (default time unit is ms)
        delay(1000L) 
        
        // print after delay
        println("World!") 
    }
    // main thread continues while coroutine is delayed
    println("Hello,") 
    
    // block main thread for 2 seconds to keep JVM alive
    Thread.sleep(2000L) 
}

Coroutines also supports more complex operations such as Job Joining, Channel,                     Shared Context and Parents. Details and more usages can be read here.

协程还支持更复杂的操作,例如作业合并,通道,共享上下文和父级。 详细信息和更多用法可以在这里阅读。

结语 (Wrapping it up)

To sum it up, it's very easy to start using Kotlin, you can code Kotlin very similar to how you code Java. And also, Kotlin has provided several features that can give you edges over using Java.

综上所述, 开始使用Kotlin非常容易,您可以将Kotlin编码为与Java编码非常相似的代码。 而且, Kotlin还提供了一些功能,这些功能可以使您在使用Java方面具有优势。

Sure, Java is still going strong at the moment. But it's never wrong to start learning something new. We, as programmers, need to embrace lifetime learning and never stop learning. The best thing about Kotlin is how easy it is to migrate from Java.

当然,Java现在仍然很强大。 但是,开始学习新东西永远不会错。 作为程序员,我们需要接受终身学习,并且永不停止学习。 关于Kotlin最好的事情是从Java迁移有多容易。

Thanks for reading. I hope you do enjoy and hopefully it would be of a good use! Good luck in exploring Kotlin, and see you next time.

谢谢阅读。 希望您喜欢,并希望它会很有用! 祝您探索Kotlin好运,下次再见。

翻译自: https://www.freecodecamp.org/news/still-using-java-for-android-development-you-should/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值