Kotlin equivalent of class properties, constructors, empty parameter constructors, getters and setters - kotlin

I am currently practicing in developing kotlin and as of now I seem to get confused with kotlin's class structure.
this is a code in java
//properties
private String var;
//constructor
public SampleClass(String var){
this.var = var;
}
public SampleClass(){
}
//getters and setters
public String getVar(){
return this.var;
}
public String setVar(String var){
this.var = var;
}
what's the kotlin equivalent of this ?

This is the equivalent Kotlin code for your Java code:
class SampleClass(var `var`: String? = null)
There are a few things to note:
Your Java snippet above omits the wrapping class SampleClass code
Your setVar() indicates that it returns a String, but it's actually void. I assume you intended for it to have a void return type.
Your property var is not ideal for Kotlin, because it's a reserved word. That's why we have to escape it with backticks. (It could also be kind of confusing in Java 10, since var is a reserved type name there now).
Here's why this one-liner is equivalent to the Java listing.
The constructor part - the part between the parentheses - can be used to accept constructor arguments, but by putting the Kotlin keyword var at the beginning, we tell Kotlin that we want this to also be a property. Kotlin will create a getter and setter for it.
The String? part makes this property of type nullable String.
Instead of creating two different constructors, we just give our var property argument a default value of null by using = null. When creating this class from Java, it'll still show up as two constructors.
If you're using IntelliJ or Android Studio, you can tell it to convert any Java class to Kotlin. Just open the class file, and go to the Code menu, and choose Convert Java file to Kotlin file. It won't necessarily generate very idiomatic code (e.g., it might create two constructors instead of using a default for the constructor argument), but it'll get you started.

For "what is Kotlin equivalent of some code in Java", there is an universal answer: copy the Java code and paste it into a Kotlin file in IDEA/Android Studio. Or convert the entire file.
On the web, you can use https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt.

Related

Where is this kotlin expression described in the documentation?

I have this kotlin function, and I undersatand that the expression : row.map(Char::digitToInt), converts a Char into an Int.
What I need, is more explanation regarding Char::digitToInt.
How can I relate the use of :: in the kotlin documentation?
Thank's in advance for your reply.
private fun parseInput(input: List<String>): Array<IntArray> =
input.map { row: String ->
row.map(Char::digitToInt).toIntArray()
}.toTypedArray()
As stated in the docs this is a class reference:
Class References: The most basic reflection feature is getting the
runtime reference to a Kotlin class. To obtain the reference to a
statically known Kotlin class, you can use the class literal syntax:
val c = TestClass::class //The reference is a value of type KClass.
Note that a Kotlin class reference is not the same as a Java class
reference. To obtain a Java class reference, use the .java property on
a KClass instance.
It’s also the syntax for method references as in this simple example:
myList.forEach(::println)
It refers to println defined in Kotlin Standard library.

Dlang: why are constructors not inherieted?

Is there a way to not have to repeatidly write this(parent class args) {super(parent class args);} when the arguments are exactly the same?
The code:
class Parent {
string name;
this(string name) {
this.name = name;
}
}
class Child : Parent {
}
unittest {
auto child = new Child("a name");
assert(child.name == "a name");
}
https://run.dlang.io/is/YnnezI
Gives me the compilation error:
Error: class onlineapp.Child cannot implicitly generate a default constructor when base class onlineapp.Parent is missing a default constructor
Java and C# don't inherit constructors either (unless that's changed in the last few years - I don't think C++ allowed it either until c++11), and D follows the same reasoning so you can read more by looking up things about them.
Basically though the reason is that subclasses must have their own unique state - at very least stuff like the vtable even if you don't declare any of your own variables - and thus a unique constructor is required. Otherwise you can have uninitialized members.
And if inheritance went the whole way, since Object has a this(), new AnyClass(); would compile and lead to a lot of invalid objects. (In regular D, if you declare any ctor with arguments, it disables the automatically-generated zero arg one.)
Now, D could in theory do what C++ does and auto-generate other args too... it just doesn't. Probably mostly because that is a relatively new idea in C++ and D's class system is primarily based on Java's older system.
But all that said, let me show you a trick:
this(Args...)(auto ref Args args) { super(args); }
stick that in your subclass and you basically inherit all the parent's constructors in one go. If the super doesn't compile for the given args, neither will this, so it doesn't add random things either. You can overload that with more specific versions if needed too, so it is a reasonable little substitute for a built-in language feature.

Utils class in Kotlin

In Java, we can create an utilities class like this:
final class Utils {
public static boolean foo() {
return false;
}
}
But how to do this in Kotlin?
I try using functions inside object:
object Utils {
fun foo(): Boolean {
return false
}
}
But when call this method from Java code it need to add INSTANCE. Ex: Utils.INSTANCE.foo().
Then I change to declare it as top-level function (without class or object):
#file:JvmName("Utils")
#file:JvmMultifileClass
fun foo(): Boolean {
return true
}
Then I can call Utils.foo() from Java code. But from Kotlin code I got Unresolved reference compiler error. It only allow be to use foo() function directly (without Utils prefix).
So what is the best approach for declaring utils class in Kotlin?
The last solution you've proposed is actually quite idiomatic in Kotlin - there's no need to scope your function inside anything, top level functions are just fine to use for utilities, in fact, that's what most of the standard library consists of.
You've used the #JvmName annotation the right way too, that's exactly how you're supposed to make these top level functions easily callable for Java users.
Note that you only need #JvmMultifileClass if you are putting your top level functions in different files but still want them to end up grouped in the same class file (again, only for Java users). If you only have one file, or you're giving different names per file, you don't need this annotation.
If for some reason you want the same Utils.foo() syntax in both Java and Kotlin, the solution with an object and then #JvmStatic per method is the way to do that, as already shown by #marianosimone in this answer.
You'd need to use #JvmStatic for that:
In Kotlin:
object Utils {
#JvmStatic
fun foo(): Boolean = true
}
val test = Utils.foo()
In Java:
final boolean test = Utils.foo()
Note that the util class you used in Java was the only way to supply additional functions there, for anything that did not belong to a particular type or object. Using object for that in Kotlin does not make any sense. It isn't a singleton, right?
The second approach you mentioned is rather the way to go for utility functions. Internally such functions get translated to static ones and as you can see they become the static util classes in Java you are searching for, as you can't have standalone functions in Java without a class or enum. In Kotlin itself however they are just functions.
Some even count utility classes to the anti-patterns. Functions on the other hand make totally sense without a class or object whose name hasn't so much meaning anyway.

What is the purpose of empty class in Kotlin?

I was going through Kotlin reference document and then I saw this.
The class declaration consists of the class name, the class header
(specifying its type parameters, the primary constructor etc.) and the
class body, surrounded by curly braces. Both the header and the body
are optional; if the class has no body, curly braces can be omitted.
class Empty
Now I'm wondering what is the use of such class declaration without header and body
Empty classes can be useful to represent state along with other classes, especially when part of a sealed class. Eg.
sealed class MyState {
class Empty : MyState()
class Loading : MyState()
data class Content(content: String) : MyState()
data class Error(error: Throwable) : MyState()
}
In this way you can think of them like java enum entries with more flexibility.
tldr: they want to demonstrate it's possible
even an empty class is of type Any and therefore has certain methods automatically. I think in most cases, this does not make sense, but in the documentation case it's used to show the simplest possible definition of a class.
The Java equivalent would be:
public final class Empty {
}
From practical programmer day to day perspective empty class makes no much sense indeed. There are however cases where this behavior is desirable.
There are scenarios where we want to make sure that we want to define a class and at the same time, we want to make sure that instance of this class will never be created (type created from such class is called empty type or uninhabited type).
Perfect example of this is Kotlin Nothing class with do not have class declaration header and body (notice that it also have private constructor)
https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/Nothing.kt
There are few usages for Nothing in Kotlin language. One of them would be a function that does not return a value (do not confuse this with Unit where the function returns actually returns a value of type Unit). A typical example is an assertFail method used for testing or method that exits current process. Both methods will never actually return any value yet we need to explicitly say tell it to a compiler using special type (Nothing).
fun assertFail():Nothing {
throw Exception()
}
Nothing can be also used with start projections where type Function<*, String> can be in-projected to Function<in Nothing, String>
Another usage for empty class is type token or placeholder:
class DatabaseColumnName
class DatabaseTableName
addItem(DatabaseColumnName.javaClass, "Age")
addItem(DatabaseTableName.javaClass, "Person")
...
getItemsByType(DatabaseTableName.javaClass)
Some languages are using empty classes for metaprogramming although I haven't explored this part personally:
Advantages of an empty class in C++
An example of empty class usage from Spring Boot framework:
#SpringBootApplication
class FooApplication
fun main(args: Array<String>) {
runApplication<FooApplication>(*args)
}
It doesn't make much sense as a final result. However it can be useful in active development and at a design time as a placeholder of some sort, which may be expanded in the future. Such terse syntax allows you to quickly define such new types as needed. Something like:
class Person (
val FirstName: String,
val LastName: String,
// TODO
val Address: Address
)
class Address
I think main reason this is specifically mentioned in documentation is to demonstrate, that language syntax in general can be terse, not that it is specifically created for common usage.
Sealed classes, in a sense, an extension of enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances which can contain state.
reference

Kotlin make me crash! Is it a Function Or a Class when I read a code?

I'm a beginner of Kotlin, there are many omitted code with Kotlin. It make me crash when I read some sample code.
Such as var map=HashMap()
I can't judge what HashMap() is function or class. I have to judge it by Hint of Android Studio. Do you have a simple way?
If I use java, it will be different code style.
Function: Map map=myFunction()
Class: Class myClass=new Class()
First, if you follow Java naming conversion, class is PascalCase and function is camelCase.
Second, it does not matter. Creating a new object is just a constructor returning an object. It does not different from a a function return an object.
I can't judge what HashMap() is function or class
Don't think of this as class or function. HashMap() is a constructor which is really a method (function) that returns an instance of an object. So there is really no need of the new keyword here, and it make for clean code.
You can identify if it's a function or a constructor based on the Name itself (the case of the name).