Skip to content

Commit 6f52e64

Browse files
committed
Add URI as inline classes
* Added Album, Artist, Playlist, Track and User * Added test for them
1 parent dd707a0 commit 6f52e64

File tree

3 files changed

+404
-0
lines changed

3 files changed

+404
-0
lines changed

build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ test {
6363

6464
compileKotlin {
6565
kotlinOptions.jvmTarget = "1.8"
66+
kotlinOptions {
67+
freeCompilerArgs = ["-XXLanguage:+InlineClasses"]
68+
}
6669
}
6770
compileTestKotlin {
6871
kotlinOptions.jvmTarget = "1.8"
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.adamratzman.spotify.utils
2+
3+
private fun String.add(type: String, length: Int = 22): String {
4+
val match = "^(?:$type:)?(.{$length})(?::.*)?$".toRegex().matchEntire(this)
5+
match?.groupValues?.get(1)?.also {
6+
return "$type:$it"
7+
}
8+
throw IllegalArgumentException("$this isn't convertible to $type uri")
9+
}
10+
11+
private fun String.remove(type: String, length: Int = 22): String {
12+
val match = "^(?:$type:)?(.{$length})(?::.*)?$".toRegex().matchEntire(this)
13+
match?.groupValues?.get(1)?.also {
14+
return it
15+
}
16+
throw IllegalArgumentException("'$this' isn't convertible to '$type' id")
17+
}
18+
19+
20+
inline class AlbumURI(private val input: String) {
21+
val uri: String
22+
get() = input.add("spotify:album")
23+
val id: String
24+
get() = input.remove("spotify:album")
25+
}
26+
27+
inline class ArtistURI(private val input: String) {
28+
val uri: String
29+
get() = input.add("spotify:artist")
30+
val id: String
31+
get() = input.remove("spotify:artist")
32+
}
33+
34+
inline class TrackURI(private val input: String) {
35+
val uri: String
36+
get() = input.add("spotify:track")
37+
val id: String
38+
get() = input.remove("spotify:track")
39+
}
40+
41+
inline class UserURI(private val input: String) {
42+
val uri: String
43+
get() = input.add("spotify:user", 25)
44+
val id: String
45+
get() = input.remove("spotify:user", 25)
46+
47+
// inline is not supported as non-top-level-class
48+
inner /*inline*/ class PlaylistURI(private val input: String) {
49+
val uri: String
50+
get() = input.add("${this@UserURI.uri}:playlist")
51+
val id: String
52+
get() = input.remove("${this@UserURI.uri}:playlist")
53+
}
54+
55+
companion object {
56+
@Suppress("FunctionName") // "static" constructor
57+
fun PlaylistURI(input: String): PlaylistURI {
58+
return UserURI(input).PlaylistURI(input).also { it.uri /*check format*/ }
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)