# announcements

Daniele Segato

11/21/2019, 7:06 AM
Using java code i can use interface with a single method just by using the interface name, like this:
Copy code
val x = SomeInterface { }
Thanks to SAM. However when i try the same thing on kotlin interface I'm forced to create an anonymous class:
Copy code
val x = object : SomeInterface {
  fun someMethod() { }
If i instead create a type alias for it I can write it without the object ceremony but I've no way of specifying what it is:
Copy code
typealias SomeInterface = (): Unit

// ...

val x = { }
Yes i know i can do
Copy code
val x: SomeInterface = { }
But picture this situation:
Copy code
val x: SomeInterface = when (foo) {
  "A" -> { { } }
  "B" -> { { } }
I need double
, which is horrible. I think it would be much better to be able to write;
Copy code
val x = when (foo) {
  "A" -> SomeInterface { }
  "B" -> SomeInterface { }
Is there a way to do this or a way to improve the previous example?
Please can you reply in thread?


11/21/2019, 7:54 AM
I think you can declare top level function fun
SomeInterface(lambda): SomeInterface = lambda
Then you will be able to do what you want
✔️ 1

Daniele Segato

11/21/2019, 8:05 AM
Thanks for the tip, i can make it inline to remove any friction and just improve the code readability. Thanks!
it was easy afterall, didn't though of top level functions
Copy code
typealias SomeInterface = (param: SomeParam) -> SomeResult

@Suppress("NOTHING_TO_INLINE", "FunctionName")
inline fun SomeInterface(noinline lambda: SomeInterface): SomeInterface = mapper
and now I can write a more readable code :)


11/21/2019, 6:14 PM
alternatively you can add an invoke operator to the interfaces' companion object. I prefer this approach, but obviously you can't do that to a java class, though

Daniele Segato

11/22/2019, 12:21 PM
@Hullaballoonatic I'm sorry I fail to understand what you mean do you mean something like:
Copy code
interface SomeInterface {
  operator fun invoke(param: SomeParam): SomeResult
? or do you mean like this?
Copy code
interface SomeInterface {
  fun doStuff(param: SomeParam): SomeResult
  companion object {
    operator fun invoke(lambda: SomeInterface): SomeInterface = lambda
? If you meant any of those, I fail to see how they'd help in my situation / how to make use of them. Can you give an example of what you meant and how to use it? Thanks