mbonnin
11/07/2024, 5:06 PM// How do I do this in Kotlin?
interface Shape {
int area();
class Square implements Shape {
// private constructor here
private Square() {}
@Override public int area() {return 0;}
}
// more shapes...
/**
* static factory method
* Doesn't work on a Kotlin companion function because the Square constructor is private
*/
static Square square() {
return new Square();
}
}
mbonnin
11/07/2024, 5:07 PMmbonnin
11/07/2024, 5:07 PMKlitos Kyriacou
11/07/2024, 5:09 PMmbonnin
11/07/2024, 5:13 PMmbonnin
11/07/2024, 5:13 PMRob Elliot
11/07/2024, 5:19 PMRob Elliot
11/07/2024, 5:20 PMShape.Square.square()
rather than Shape.square()
.mbonnin
11/07/2024, 5:22 PMa client can still callYup, ideally I'd like to avoid that but looks like that's just not an optionrather thanShape.Square.square()
Shape.square()
mbonnin
11/07/2024, 5:24 PM**
* Symbols annotated with [PrivateConstructor] are only public for technical reasons, but you shouldn't use them.
*/
@RequiresOptIn
annotation class PrivateConstructor
internal interface Shape {
fun area(): Int
class Square @PrivateConstructor constructor() : Shape {
override fun area(): Int {
return 0
}
}
companion object {
fun square(): Square {
@OptIn(PrivateConstructor::class)
return Square()
}
}
}
mbonnin
11/07/2024, 5:24 PMKlitos Kyriacou
11/07/2024, 5:25 PMShape.Square
publicly exposed? One idiom is to have Shape.square()
return a privately defined Square
using a return type of Shape
but with all the behaviour of a `Square`:
interface Shape {
fun area(): Int
private class Square : Shape {
override fun area(): Int {
return 0
}
}
companion object {
fun square(): Shape {
return Square()
}
}
}
This way it doesn't matter that the Square
constructor is public, as your users can't construct a Square
directly.mbonnin
11/07/2024, 5:27 PMDo you need to have the typeYes, in my use case,publicly exposed?Shape.Square
Shape
is actually a sealed interface and the user must be able to switch on the different casesmbonnin
11/07/2024, 5:29 PMephemient
11/07/2024, 6:43 PMprivate
constructor gets a package-private bridge so that it can be accessed from outside the classephemient
11/07/2024, 6:46 PMprivate
without that bridgeephemient
11/07/2024, 6:46 PMmbonnin
11/07/2024, 7:08 PM