'How to tell the difference between Java and Kotlin code?

As a beginner to Android app development, I am finding code examples that do not identify whether they are written in Java or Kotlin. Even StackOverflow questions frequently omit the language tag.

Is there an easy "tell" in the code where you can immediately see which language is used? For example, I can distinguish C and C++ very quickly from certain elements of the syntax, header use, and library functions.

Are there any quick and "obvious" ways to distinguish Java from Kotlin? I want to be exploring Kotlin and not adding to my (immense) confusion by studying irrelevant code.



Solution 1:[1]

some obvious traits for kotlin:

  • as already mentioned the most obvious is semicolons, although you can add them and they will just be ignored

  • variables marked with question marks (nullability) val foo:String? and the usage of val/var/lateinit

  • class Foo : Something() <-- this is inheritance, there's no extends or implements

  • if files are involved, kotlin files end with .kt

  • any reference to companion object


personally for me the biggest indicator:

fun :) function declaration :

fun foo(): String

Solution 2:[2]

If the code has used "val", "var" keywords then 99% it is Kotlin.

Solution 3:[3]

Kotlin Keywords and operators. https://kotlinlang.org/docs/keyword-reference.html

Java Language Keywords. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Most likely kotlin:

val
var
fun
nameX: TypeX
nameX : TypeX?
object: 
open class
when
@
:
sealed
!!
->
"$name or ${name}"
etc

Most likely java:

; semicolon
TypeX nameX
void
extends 
implements
public class
instanceof
etc

Solution 4:[4]

Java has mandatory semicolons ';' while Kotlin doesn't. The types in Java are int, string, char, etc while in Kotlin they are capitalized(String, Int, Long, Char), also Kotlin can infer the type of a variable most of the time ;)

Solution 5:[5]

i found this article helpful
as guys told kotlin is a language Is introduced by null safety and without any smicolons force and you can find some key in syntax like

**[fun,as,let,also,apply,val,var,lateinit,...]**

So, which one is better and should you use it? The answer to that question depends on your needs. If you’re looking for a language with solid support from Google, then Kotlin may be the best choice, as Android Studio 3 now supports Kotlin development. However, if you need speed or want an open-source project with more flexibility (especially in terms of third-party libraries), Java might be the right option for you.

refer to this article

Solution 6:[6]

If the file end with .kt, it is Kotlin.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 ocos
Solution 4 MercifulSory
Solution 5
Solution 6 Ethan