1

I have shortened the names of some frequently-used foreign functions (that I don't control) with "aliases", based on advice I received in an earlier question. This has worked nicely for extension functions; however, I have a few top-level functions I'd like to alias as well. For a simplified example, consider the generateSequence function. I want to be able to do this:

// DOES NOT COMPILE
inline val <T:Any> seq:(()->T?)->Sequence<T> get() = ::generateSequence

...but I can't because the generic must be used in the receiver type, as explained well in this answer. Is there any other way to create an alias for a top-level function (requiring generics) which preserves the inline?

EDIT: I tried using Any? and star projection right after posting the question, but I still don't think it's a good answer:

inline val seq:(()->Any?)->Sequence<*> get() = ::generateSequence

This seems boptimalsu because it compromises type-checking on the Sequence's element type, correct? Other answers/thoughts as to what could work?

sirksel
  • 747
  • 6
  • 19

1 Answers1

2

An option that you could use is a renaming import, though it is limited to a single source file:

import kotlin.sequences.generateSequence as seq

fun main(args: Array<String>) {
    seq(1) { it + 1 }.take(10).forEach(::println)
}

Apart from that, I think, the best you could do is to fall back to declaring another inline function:

inline fun <T> seq(nextFunction: () -> T?) = 
    generateSequence(nextFunction)

In fact, I'd expect the performance of this option to be better than of the one with a function reference, because using an inline property returning a function reference still has some overhead when you make a call to that reference, while this call is inlined and thus should introduce no overhead for another nested call.

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • I like your inline function approach, but I thought that returns an `illegal use of inline-parameter` error. I used the inline property because I couldn't find another way to do it inline, even after asking [this question earlier](https://stackoverflow.com/questions/47605151). Do you think the inline property (function reference) would perform worse than a function with a `noinline` lambda parameter (assuming I'm talking about a function where I can do it -- i.e., that doesn't require generics)? – sirksel Dec 07 '17 at 02:10