-
Notifications
You must be signed in to change notification settings - Fork 439
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
arrow-typeclasses/src/main/kotlin/arrow/typeclasses/Show.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package arrow.typeclasses | ||
|
||
import arrow.* | ||
|
||
|
||
/** | ||
* A type class used to get a textual representation for an instance of type [F] in a type safe way. | ||
* | ||
*/ | ||
@typeclass | ||
interface Show<in F> : TC { | ||
|
||
/** | ||
* Given an object [a] of type [F] it returns its textual representation. | ||
* | ||
* @param a object of type [F]. | ||
* @returns a [String] representing [a]. | ||
*/ | ||
fun show(a: F): String | ||
|
||
companion object { | ||
|
||
/** | ||
* Construct a [Show] instance from a function `(F) -> String` | ||
* | ||
* @param fshow function that defines a textual representation for type [F]. | ||
* @returns a [Show] instance that is defined by the [fshow] function. | ||
*/ | ||
operator inline fun <F> invoke(crossinline fshow: (F) -> String): Show<F> = object : Show<F> { | ||
override fun show(a: F): String = | ||
fshow(a) | ||
} | ||
|
||
/** | ||
* Construct a [Show] instance using object `toString`. | ||
* | ||
* @param a object of type [F]. | ||
* @returns a [Show] instance that is defined by the [F] `toString` method. | ||
*/ | ||
fun <F> fromToString(a: F): Show<F> = object : Show<F> { | ||
override fun show(a: F): String = | ||
a.toString() | ||
} | ||
|
||
/** | ||
* Retrieve a [Show] that defines the textual representation as toString() for type [F]. | ||
*/ | ||
fun any(): Show<Any?> = ShowAny | ||
|
||
private object ShowAny : Show<Any?> { | ||
override fun show(a: Any?): String = | ||
a.toString() | ||
} | ||
} | ||
} |