https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

02/24/2024, 4:40 AM
You can access a reference to a function using
::fn
. Is there a reason why this wasn't chosen as the notation for referencing a class itself rather than an instance, as opposed to having to do
Foo::class
?
y

Youssef Shoaib [MOD]

02/24/2024, 4:46 AM
Pretty sure
::Foo
references `Foo`'s constructor
Which is good to keep consistency between constructors and factory function; constructors don't need to be special on the caller side (e.g. no
new
keyword)
r

Ray Rahke

02/24/2024, 5:23 AM
Can I perform a runtime check on that to see if an instance was built with that constructor
Copy code
val thing = Foo()
fun<T: Foo> isInstance(ctor: () => T) {
  return thing is ctor
}

isInstance(::Foo)
i prefer ::Foo much more than Foo::class
maybe I could do
Copy code
return thing::class.constructor is ctor
something like that
y

Youssef Shoaib [MOD]

02/24/2024, 5:35 AM
I'd say just use reified type params instead of
::class
then:
Copy code
inline fun <reified T> Any?.isInstance() = this is T

val thing = Foo()
thing.isInstance<Foo>()
r

Ray Rahke

02/24/2024, 5:56 AM
Does that do anything in the runtime though? or is it just a type assertion
my real use case filters through a list and returns all who are instances
also, it is a vararg function. I would like to be able to ask if an object is multiple instances at once. possible?
j

Joffrey

02/24/2024, 10:53 AM
my real use case filters through a list and returns all who are instances
Then there is already
filterIsInstance<T>()
. If your use case slightly different, you can look at its implementation
r

Ray Rahke

02/24/2024, 11:11 AM
Yeah but this needs to be a helper method that delegates to taht
entity.get(::Foo) should internally call filterIsInstance
so I don't have to do entity.components.filterIsInstance<T>() - that is verbose
it should work... ill try
j

Joffrey

02/24/2024, 11:13 AM
Then use a reified type argument in your helper function, and you can achieve the same effect as Youssef mentioned
The usual approach is to have a function taking parameters of type
KClass
and write an inline reified wrapper on top
It can be a vararg of
KClass
and then a few inline reified wrappers taking 1, 2, 3, 4 type parameters.
But your use case with multiple type checks is a bit strange. If you need to type check multiple things, it should be for a reason, and this reason is probably sufficient to make a supertype for those. Otherwise the check doesn't bring any extra type safety on the results
1