Is there anyway in Kotlin to have two constructors...
# getting-started
r
Is there anyway in Kotlin to have two constructors in class with both having lists as an argument but with different types in them? For example:
Copy code
constructor(aList : List<A>)  /* Main constructor */
constructor(bList : List<B>) : this (bList.toListA())
I get the following:
Copy code
Platform declaration clash: The following declarations have the same JVM signature ((Ljava/util/List;)V):
How do I distinguish between them?
m
I don't think you can with constructors. Instead you probably need to create factory methods and use the JvmName annotation to make the name different for Java callers. You can use the name of the class for the factory methods if you want it to look like a constructor. Probably keep the List<A> one as a constructor and make the List<B> a function.
👍🏼 1
r
Thanks! Came to the same conclusion just a minute ago. You can even make the function look as a constructor by overriding the
invoke
operator. Still... it kind of feels like a hack to me. Pretty weird Kotlin doesn't offer a better solution.
c
To my knowledge, it is considered bad practice to use Companion.invoke to mimic a constructor. The better practice is to have a top-level function that has the same name as the class (with the capitals and everything).
1
(for example the
List
factory in the standard library)
Also for the ‘lack of better solution', Project Valhalla will bring runtime reified generics to the JVM, maybe then?
e
as far as I'm aware, there is still no spec for generic specialization. Valhalla has implemented L-world types but not https://openjdk.java.net/jeps/218
d
I'd love top level functions more if intellij didn't remove the class icon from the Kotlin file.
2
y
Haha, felt something same at the beginning of my Kotlin programming :) Now this problem in my mind fixed and it's not problem. Additionally the idea now does not provide a
function name
warning in case if such functions have the same return type as its name.
c
@Dominaezzz then you can put it in the companion object and
import static
it. Honestly though, you shouldn't architecture your code just so you have a specific icon on your screen, especially when that stops you from using one of the most important features of the language
💯 1
r
OCD, gift and curse at the same time.
☝🏼 1
1