Reputation: 9106
Suppose I have an interface
interface A {
fun calculate(n: Int): Int
}
I'd like to implement A
in a class B
(say) so that the calculation
is provided in B
's constructor, something like:
class B (f : (Int) -> Int) : A {
override fun calculate(n: Int): Int //...somehow assign f to calculate
}
Can this be done without making f
a property of B
?
Hmm... this works:
interface A {
val calculate: (n: Int) -> Int
}
class B(f: (Int) -> Int) : A {
override val calculate = f
}
Can someone explain the intended syntactic difference between fun
and val
here? I am aware of Function definition: fun vs val but would like to get a 'language level' understanding.
Upvotes: 1
Views: 108
Reputation: 97328
The simplest way to implement this is:
class B(val f : (Int) -> Int) : A {
override fun calculate(n: Int): Int = f(n)
}
Upvotes: 3
Reputation: 31264
Yes, this can be done without making f
a property of B
. e.g. By using class delegation to an object expression:
class B(f: (Int) -> Int) : A by object : A {
override fun calculate(n: Int) = f(n)
}
Even so, a private val
seems more appropriate for this simple example.
Upvotes: 1