kotlin_poet_rs/spec/
parameter.rs1use crate::io::RenderKotlin;
2use crate::spec::{Annotation, CodeBlock, Name, Type};
3use crate::spec::annotation::{mixin_annotation_mutators, AnnotationSlot};
4use crate::tokens;
5
6#[derive(Debug, Clone)]
7pub struct Parameter {
8 name: Name,
9 parameter_type: Type,
10 default_value: Option<CodeBlock>,
11 annotation_slot: AnnotationSlot,
12}
13
14impl RenderKotlin for Parameter {
15 fn render_into(&self, block: &mut CodeBlock) {
16 block.push_renderable(&self.annotation_slot);
17 block.push_renderable(&self.name);
18 block.push_static_atom(tokens::COLON);
19 block.push_space();
20 block.push_renderable(&self.parameter_type);
21 if let Some(default_value) = &self.default_value {
22 block.push_space();
23 block.push_static_atom(tokens::ASSIGN);
24 block.push_space();
25 block.push_renderable(default_value);
26 }
27 }
28}
29
30impl Parameter {
31 pub fn new<NameLike: Into<Name>, TypeLike: Into<Type>>(name: NameLike, parameter_type: TypeLike) -> Parameter {
32 Parameter {
33 name: name.into(),
34 parameter_type: parameter_type.into(),
35 default_value: None,
36 annotation_slot: AnnotationSlot::horizontal(),
37 }
38 }
39
40 pub fn default_value<CodeBlockLike: Into<CodeBlock>>(mut self, default_value: CodeBlockLike) -> Parameter {
41 self.default_value = Some(default_value.into());
42 self
43 }
44
45 mixin_annotation_mutators!();
46}
47
48#[cfg(test)]
49mod tests {
50 use std::str::FromStr;
51 use crate::io::RenderKotlin;
52 use crate::spec::{Annotation, ClassLikeTypeName, CodeBlock, Name, Parameter, Type};
53
54 #[test]
55 fn test_rendering() {
56 let parameter = Parameter::new(
57 Name::from("name"),
58 Type::string(),
59 );
60
61 assert_eq!(
62 "name: kotlin.String",
63 parameter.render_string()
64 )
65 }
66
67 #[test]
68 fn test_rendering_with_default() {
69 let parameter = Parameter::new(
70 Name::from("age"),
71 Type::int(),
72 ).default_value(CodeBlock::atom("25"));
73
74 assert_eq!(
75 "age: kotlin.Int = 25",
76 parameter.render_string()
77 )
78 }
79
80 #[test]
81 fn test_rendering_with_annotation() {
82 let parameter = Parameter::new(
83 Name::from("age"),
84 Type::int(),
85 ).annotation(
86 Annotation::new(
87 ClassLikeTypeName::from_str("io.github.lexadiky.MyAnnotation")
88 .unwrap()
89 )
90 ).annotation(
91 Annotation::new(
92 ClassLikeTypeName::from_str("io.github.lexadiky.OtherAnnotation")
93 .unwrap()
94 )
95 );
96
97 assert_eq!(
98 "@io.github.lexadiky.MyAnnotation() @io.github.lexadiky.OtherAnnotation() age: kotlin.Int",
99 parameter.render_string()
100 )
101 }
102}