https://kotlinlang.org logo
t

trevjones

09/08/2017, 4:32 PM
Is there anything you could do with an inline class that you can’t do with an inline func that returns an
object: WhateverInterfaceOrClass()
either way it ends up as a template for the compiler no?
k

karelpeeters

09/08/2017, 4:36 PM
I'm not sure I'm understanding you, can you give some example code?
t

trevjones

09/08/2017, 4:40 PM
something like:
Copy code
inline fun TabLayout.onTabReselected(crossinline onTabReselected: (tab: TabLayout.Tab) -> Unit) {
    addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabReselected(tab: TabLayout.Tab) = onTabReselected(tab)

        override fun onTabUnselected(tab: TabLayout.Tab?) {}

        override fun onTabSelected(tab: TabLayout.Tab?) {}
    })
}
only instead of the set
just return it
let me do a new one that one is bad
Copy code
abstract class MyInlineClass<T> {
    abstract fun someFactoryMethod(): T
}

inline fun <T> someInlineClass(crossinline someFunc: () -> T) : MyInlineClass<T> {
    return object : MyInlineClass<T>() {
        override fun someFactoryMethod(): T {
            return someFunc()
        }
    }
}
k

karelpeeters

09/08/2017, 4:48 PM
Ah I meant inline in a "the class doesn't actually exist"-way. An example:
Copy code
inline data class Point(
    val x: Int
    val y: Int
) {
    fun opposite() = Point(-x, -y) //implicit inline
    
    //generated toString, equals, ...
}
fun foo(point: Point) {
    println(point.opposite())
}
would be compiled to
Copy code
fun foo(x: Int, y: Int) {
    println("Point(x=${-x}, y=${-y})")
}
t

trevjones

09/08/2017, 4:58 PM
so like a value type?
k

karelpeeters

09/08/2017, 4:59 PM
Well values types have pass-by-value semantics, inline classes not necessarily.
t

trevjones

09/08/2017, 5:28 PM
seems like you save one allocation and end up with a java interop story that is a mess
potentially a mess
k

karelpeeters

09/08/2017, 5:30 PM
It can make a significant difference in high-performance situations like game physics.
Actually Java interop wouldn't be too bad, the Java-code would just see the non-inline versions of the methods of the
inline
class.
Similar to how inline extension functions work today.
3 Views