I have noticed that we can create classes in Kotlin without curly braces like below.
//Example classFile.kt
class Empty
class SecondEmpty
fun firstMethod() {
}
My question is, why we need such feature? in which situation we can use this?
In the above example, I have written a method called firstMethod() how can I call that from the other objects?
Empty classes have been discussed in What is the purpose of empty class in Kotlin? already.
Regarding your firstMethod: in Kotlin, we have so called top-level functions. These can be defined in any file without an enclosing class. Another example for this is main which is defined top-level in most cases.
How to call top-level functions?
You can simply import the function into other files and call them. For instance, if firstMethod were defined in com/x/Example.kt (package com.x), you may import com.x.firstMethod in other Kotlin files and call that method.
For Java, it’s important to know, that top-level functions are compiled into a class as static members. As for the example above, you can call com.x.ExampleKt.firstMethod from Java.
Related
Is there any way to get only the declared members of a class (not inherited) with Kotlin Reflection?
Something equivalent to getDeclaredMethods(), or ...Fields(), in Java, but for members and JVM free, which:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
Or like a binding flag, such as BindingFlags.DeclaredOnly of dotnet.
Because the reflection is based on the class, So the following is only for the kotlin/JVM, not suitable for the Kotlin/JS or Kotlin/Native.
For the Kotlin/JS it supports limit, for detail, you can see this
document
The only supported parts of the API are: (::class),KType and typeOf
Firstly, you can use the SomeClass::class.java.declaredMethods to get the
getDeclaredMethods. That is the java method. Because the Kotlin file after compiled it is still a class. so you can directly use it.
You can also add the kotlin reflect to get the KClass, then use the declaredFunctions to get. Here is the Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
For how to get the KClass, you can use the following code
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
Besides the method, the other property you can also get. such as
declaredMembers
Returns all functions and properties declared in this class. Does
not include members declared in supertypes.
allSuperclasses
functions
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
you can read the document using it.
Is it a good idea to cut my code anywhere around the project in other classes using extension functions?
I mean what is the point?For what exactly a class fun can leak to other classes?
Friends, I'm new to Kotlin and I appreciate if anyone can provide a real example of using extension fun in kotlin.
class Car{
//any code you imagine
}
class Garage{
//any code
fun Car.boost(){
//boost implementation
}
}
As stated in Kotlin Coding Conventions, extension functions are a good practice:
Use extension functions liberally. Every time you have a function that
works primarily on an object, consider making it an extension function
accepting that object as a receiver.
There are a few reasons for that:
Extension functions keep your class small and easy to reason about
Extension functions force you to have good API, since they cannot access any private members of your class
Extension functions have zero cost on performance, since they're simply rewritten by Kotlin compiler into static methods, with method receiver (the class you're extending) as its first argument
I'm wondering what is the best way to structure functional code in Kotlin.
I don't want to create unnecessary objects (and put functions in a closed scope) to group my functions with. I heard I can group functions by packages and put them in the top level of a package. I've also seen in Arrow library that functions are grouped in interface companion objects as extension functions and this looks the best except the fact I need to create a companion object.
Object way:
object Container {
fun myFunc() = ...
}
...
Container.myFunc()
Package way:
package myPackage
fun myFunc() = ...
...
myPackage.myFunc()
Arrow way:
interface Container {
companion object {
fun Container.myfunc() = ...
}
}
...
Container.myFunc()
What is the best way to structure my functions and group them using Kotlin? I want to keep a pure functional style, avoid creating any sort of objects, and be able to easily navigate to functions by namespaces like:
Person.Repository.getById(id: UUID)
If I understand you correctly, you're looking for the concept of namespaces (structured hierarchical scope for accessing symbols).
Kotlin does not support namespaces, but as you found out, there are different ways of having similar functionality:
object declarations. They pretty much fulfill the needs, however they lead to creation of an actual object in JVM and introduce a new type, which you don't need. The Jetbrains team generally discouraged the use of objects as namespaces, but it's of course still an option. I don't see how companion objects inside interfaces add any value. Maybe the idea is to limit the scope to classes which implement the interface.
Top-level functions. While possible, top-level functions in Kotlin pollute the global namespace, and the call-site does not let you specify where they belong. You could of course do workarounds, but all of them are rather ugly:
Fully qualify the package com.acme.project.myFunc()
Use a deliberately short, but no longer domain-representing package functional.myFunc()
Call function without package, but with prefix package_myFunc()
Extension functions. If the functionality is closely related to the objects it's operating on, extension functions are a good option. You see this for the Kotlin standard collections and all their functional algorithms like map(), filter(), fold() etc.
Global variables. This does not add much over the object approach, just prevents you from introducing a named type. The idea is to create an anymous object implementing one or more interfaces (unfortunately, without interfaces the declared functions are not globally accessible):
interface Functionals {
fun func(): Int
}
val globals = object : Functionals {
override fun func() = 3
}
It is mainly handy if your object implements different interfaces, so that you can pass only a part of the functionality to different modules. Note that the same can be achieved with objects alone, as they can implement interfaces too.
I am trying to interface with TeamCity using Kotlin.
When you convert a project to Kotlin (from .xml) you will have a file called Project.kt which is where you can set all your configurations.
With no editing mine looks like this:
object Project : Project(/* Some Function Literal with Receiver */)
This looks like circular inheritance? There are imports that I am omitting, but surely that wouldn't make that big of a difference? Could the name be interpreted in different ways depending on where it appears in the file?
My mind is interpreting the object signature like this:
object = Object declaration for singleton.
Project (first occurrence) = Name of object.
: = Inheritance marker.
Project (second occurrence) = Base class to inherit from.
() = Constructor call to the base class.
Is this circular inheritance or have I missed something big about Kotlin? I have looked here and here and can't seem to find my answer.
Assuming qualified classes other.Project and my.Project, you'd have two different classes defined with the same name, in different packages.
Since my.Project is defined as a Singleton, you cannot extend from it and the actual base class is other.Project. Kotlin is clever enough to differentiate. If you would try to do the same with a class declaration, you'd get a circular inheritance.
You could even try to force extending from the Singleton explicitly, but then you'll have the error Cannot inherit from a Singleton. So basically this only works well if you imported the right classes.
I work with a codebase where there are many classes with thousands of lines of code. I've noticed inconsistencies in style concerning prepending class names when using their methods and I'm trying to figure out the previous developer's reasoning. If we
import GeneralCode
in Class A, is it bad practice to write
GeneralCode.DoSomething()
in Class A since we already imported it (instead of simply using DoSomething())? I would think so, but I suppose it's also nice to know which methods come from which classes at a glance, since Class A imports many classes and uses methods from several of them.
EDIT: This is for VB.NET, not Java (sorry for the wrong tag, rough morning). I am new to VB.NET but GeneralCode and DoSomething() are not declared as static, neither is the import in Class A.
Might be something to do with VB.NET, but DoSomething() can indeed be used with or without prepending GeneralCode.
A method need to be prefixed with
The class name if it's a static method.
The name of the instance when it's not a static method.
Unless you are calling a method from your own class.